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

时间:2012-10-07 18:05:39

标签: c#

我是C#的新手,并且已经制作了一些有用的控制台应用程序,例如Hello World和BMI Calculator。

我正在尝试将重量转换器从英制转换为公制,反之亦然,但我在让用户选择他们想做的事情时遇到了麻烦。这是我正在努力解决的代码段:

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

3 个答案:

答案 0 :(得分:3)

使用switch/ caseif/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;
}

答案 1 :(得分:2)

您的if语句应如下所示:

if (choice  == 1)
{

}

如果您有多个代码行属于if,则需要将它们包裹在大括号{}中,如上所述。

答案 2 :(得分: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();