C#值始终为0控制台应用程序

时间:2014-03-23 08:21:12

标签: c# console-application calculator

我不知道为什么我的BMI值总是=到0.我正在编程noob我缺少什么?除此之外我的if语句好吗?我错过了什么?

    static void Main(string[] args) {
        double WeightKg = 0.0, HeightCm = 0.0, Weightlbs = 0.0, WeightOz = 0.0, BMI = 0.0, Feet = 0.0, Inches = 0.0;
        int BMIOption;
        string AnotherConversion;

        string BMIMenu = ("Which Measurement You Want to use to enter the weight and height?"
                        + "\n1)Enter 1 for Metric"
                        + "\n2)Enter 2 for British Imperial:");
        Console.Write(BMIMenu);
        BMIOption = int.Parse(Console.ReadLine());

        if (BMIOption == 1) {
            Console.Write("\nPlease Enter your Weight in Kilogram (kg):");
            WeightKg = int.Parse(Console.ReadLine());
            Console.Write("\nPlease Enter your Height in in centimetres (cm):");
            HeightCm = int.Parse(Console.ReadLine());

            BMI = WeightKg / (HeightCm * HeightCm);

            if (BMI >= 35) {
                Console.WriteLine("\nYour BMI is {0:C},Severe Obesity", BMI);
            } else if (BMI >= 30) {
                Console.WriteLine("\nYour BMI is {0:C},Obese", BMI);
            } else if (BMI >= 25) {
                Console.WriteLine("\nYour BMI is {0:C},OverWeight", BMI);
            } else if (BMI >= 18.5) {
                Console.WriteLine("\nYour BMI is {0:C},Healthy BodyWeight", BMI);
            } else if (BMI <= 18.5) {
                Console.WriteLine("\nYour BMI is {0:C},UnderWeight", BMI);
            }//End if

            Console.Write("\nWould you like to make an another conversion? \n\n(Enter Y to make an another conversion/Enter any other key to exit):");

            Console.ReadKey();

3 个答案:

答案 0 :(得分:2)

BMI以米为单位计算,而不是厘米。因此,您需要将HeightCm转换为HeightM。如果你不这样做,你会得到非常小的数字,然后打印为0。

double HeightM = HeightCm / 100.0;
BMI = WeightKg / (HeightM * HeightM);

此外,在解析时,请使用double.Parse而不是int.Parse。它现在的方式,你只会解析没有小数部分的数字。

答案 1 :(得分:0)

在这一行:

BMI = WeightKg / (HeightCm * HeightCm);

结果非常小(小于1)。举个例子,WeightKg为55,HeightCm为165.结果大约为0.002。

当您将其显示为{0:C}时,它显示为零。使用{0:G}查看实际值。

答案 2 :(得分:0)

即便如此,你的公式也是错误的,因为Martin说你必须用双重AND

替换int.Parse
BMI = WeightKg / ((HeightCm/100) * (HeightCm/100));

用它来计算它是HEIGHT IN METERS :)