3

我是 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语句吗?

4

3 回答 3

3

使用switch/ caseif/else这里是开关/案例的示例

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;
}
于 2012-10-07T18:08:48.343 回答
2

您的 if 语句应如下所示:

if (choice  == 1)
{

}

如果您有多个代码行,那么它们需要像上面那样if用花括号括起来。{}

于 2012-10-07T18:07:23.710 回答
0
        int pounds;           
        int kilo;              


        Console.WriteLine("Please enter (1)lb. conversion(2) kg. conversion");
        int userNumber = int.Parse(Console.ReadLine());


        if (userNumber == 1)
        {
            Console.WriteLine("Please enter the weight(in kilograms) you would like to convert in pounds.");
            pounds = Int32.Parse(Console.ReadLine());

            Console.WriteLine("The weight in pounds is:{0:F3}", pounds / 2.2);
        }
        else
        {
            Console.WriteLine("Please enter the weight(in pounds) you would like to conver in kilograms");
            kilo = Int32.Parse(Console.ReadLine());
            Console.WriteLine("The weight in kilograms is:{0:F3}", kilo * .45);
        }
        Console.ReadLine();
于 2013-01-12T15:11:01.350 回答