3

私は 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ステートメントで可能ですか?

4

3 に答える 3

3

使用するswitch/ caseか、if/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 に答える