首页 > 解决方案 > 有没有办法从不同的方法调用变量?

问题描述

我正在尝试构建一个 BMI 计算器,而我唯一可以在主函数中的是方法调用。每当我运行以下代码时,计算答案都不会打印。我该如何解决?

public static Double EnterWeight(object sender, EventArgs e)
{
    Console.Write("Enter Your Wieght In Pounds: ");
    double Rweight = Convert.ToDouble(Console.ReadLine());
    return Rweight;
}

public static double EnterHeight(object sender, EventArgs e)
{
    Console.Write("Enter Your Height in Inches: ");
    double Rheight = Convert.ToDouble(Console.ReadLine());
    return Rheight;
}

public static double Calculation(double height, double weight)
{
    double BMI = (weight / Math.Pow(height, 2) * 703);
    return BMI;
}

static void Main(string[] args)
{
    string name = EnterName();
    //Console.WriteLine(name);
    double weight = EnterWeight();
    //Console.WriteLine(weight);
    double height = EnterHeight(object sender, EventArgs e);
    //Console.WriteLine(height);
    double BMI = Calculation(height, weight);
    Console.WriteLine("Your BMI is: ", BMI);
}

我用于测试的矿井中有一些额外的线。

结果只是一片空白

标签: c#

解决方案


You are using the Console.WriteLine incorrectly. You need to use {argumentNumber} to indicate what argument to print and where in the string. Considering the following (I had to make some additional adjustments to get your code to compile. However, to answer your direct question, your BMI is not printing out because you are using Console.WriteLine slightly wrong.

    public static Double EnterWeight()
    {
        Console.Write("Enter Your Wieght In Pounds: ");
        double Rweight = Convert.ToDouble(Console.ReadLine());
        return Rweight;
    }

    public static double EnterHeight()
    {
        Console.Write("Enter Your Height in Inches: ");
        double Rheight = Convert.ToDouble(Console.ReadLine());
        return Rheight;
    }

    public static double Calculation(double height, double weight)
    {
        double BMI = (weight / Math.Pow(height, 2) * 703);
        return BMI;
    }
    static void Main(string[] args)
    {
        //string name = EnterName();
        //Console.WriteLine(name);
        double weight = EnterWeight();
        //Console.WriteLine(weight);
        double height = EnterHeight();
        //Console.WriteLine(height);
        double BMI = Calculation(height, weight);

        // Notice the {0}. I tell it where in the string to print the
        // argument I passed in out, and the number indicates which argument 
        // to use. Most of .NET formatting works like this.
        Console.WriteLine("Your BMI is: {0}", BMI); 


    }

And additional strategy is to use the $"" string where you can do the following:

        Console.WriteLine($"Your BMI is: {BMI}");

推荐阅读