gpt4 book ai didi

c# - 控制台重量转换器用户选择

转载 作者:行者123 更新时间:2023-11-30 15:02:20 26 4
gpt4 key购买 nike

我是 C# 的新手并且制作了一些工作控制台应用程序,例如 Hello World 和 BMI 计算器。

我正在尝试制作一个从英制到公制的重量转换器,反之亦然,但我无法让用户选择他们想要做的。这是我正在努力处理的代码段:

decimal pounds;
decimal poundsconverted;
decimal kilo;
decimal kiloconverted;
string choice;

Console.WriteLine ("Press 1 to convert from imperial to metric");
Console.WriteLine ("Press 2 to convert from metric to imperial");
choice = Console.ReadLine();

if (choice (1))
Console.WriteLine ("Please enter the weight you would like to convert in pounds (lbs) ex. 140");
pounds = Convert.ToDecimal (Console.ReadLine());
poundsconverted=pounds/2.2;
Console.WriteLine("The weight in kilograms is:{0:F3}", poundsconverted);

if (choice (2))
Console.WriteLine ("Please enter the weight you would like to conver in kilograms (kg) ex. 80");
kilo = Convert.ToDecimal (Console.ReadLine());
kiloconverted=pounds*2.2;
Console.WriteLine("The weight in pounds is:{0:F3}", kiloconverted);

我的问题是 if 语句。我尝试了多种格式但无济于事。有没有更好的方法来做到这一点?是否可以使用 if 语句?

最佳答案

使用switch/case 或者if/else 这里是switch/case的例子

decimal pounds;
decimal poundsconverted;
decimal kilo;
decimal kiloconverted;
string choice;


Console.WriteLine ("Press 1 to convert from imperial to metric");
Console.WriteLine ("Press 2 to convert from metric to imperial");
choice = Console.ReadLine();
switch (choice)
{
case 1:
Console.WriteLine ("Please enter the weight you would like to convert in pounds (lbs) ex. 140");
pounds = Convert.ToDecimal (Console.ReadLine());
poundsconverted=pounds/2.2;
Console.WriteLine("The weight in kilograms is:{0:F3}", poundsconverted);
break;
case 2:
Console.WriteLine ("Please enter the weight you would like to conver in kilograms (kg) ex. 80");
kilo = Convert.ToDecimal (Console.ReadLine());
kiloconverted=pounds*2.2;
Console.WriteLine("The weight in pounds is:{0:F3}", kiloconverted);
break;
}

关于c# - 控制台重量转换器用户选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12771384/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com