变量越界

时间:2015-10-05 11:37:40

标签: c# variables

我只是在学习C#而且我创建了一个简单的程序来获取人员BMI,但我遇到的问题是,虽然我的程序可以获得其余的变量,但它无法获得。当我运行它时发生的事情是它说它不能获得weightclass变量,因为它超出了界限,而如果我从console.writeline部分代码中删除了weightclass,那么程序将运行没有问题。

Console.WriteLine("what's your weight in pounds");
    string weight = Console.ReadLine();
    float weighnum = Single.Parse(weight);
    weight = weighnum.ToString();
    Console.WriteLine("what's your height in inches");
    string height = Console.ReadLine();
    float heightnum = Single.Parse(weight);
    height = heightnum.ToString();
    Console.WriteLine("what's your gender");
    string gender = Console.ReadLine();



    float bmi = ((weighnum) / ((heightnum) * (heightnum)) * 703);
    if (bmi < 17.5 & gender == "f")
    { string weightclass = "anorexic"; }
    else if (bmi > 17.5 & bmi < 19.1 & gender == "f")
    { string weightclass = "underweight"; }
    else if (bmi > 19.1 & bmi <25.8 & gender == "f")
    { string weightclass = "normal range"; }
    else if (bmi > 25.8 & bmi < 27.3 & gender == "f")
    { string weightclass = "marginally overweight"; }
    else if (bmi > 27.3 & bmi < 32.3 & gender == "f")
    { string weightclass = "overweight"; }
    else if (bmi > 32.3 & bmi < 35 & gender == "f")
    { string weightclass = "obese"; }
    else if (bmi > 35 & bmi < 40 & gender == "f")
    { string weightclass = "severely obese"; }
    else if (bmi > 40 & bmi < 50 & gender == "f")
    { string weightclass = "morbidly obese"; }
    else if (bmi > 50  & gender == "f")
    { string weightclass = "super obese"; }
    else if (bmi < 20 & gender == "m")
    { string weightclass = "underweight"; }
    else if (bmi >= 20 & bmi <= 25 & gender == "m")
    { string weightclass = "normal range"; }
    else if (bmi > 25 & gender == "m")
    { string weightclass = "marginally overweight"; }
    else if (bmi < 20 & gender == "m")
    { string weightclass = "overweight"; }
    else if (bmi >= 20 & bmi <= 25 & gender == "m")
    { string weightclass = "obese"; }
    else if (bmi > 25 & gender == "m")
    { string weightclass = "severely obese"; }
    else if (bmi < 20 & gender == "m")
    { string weightclass = "morbidly obese"; }
    else if (bmi >= 20 & bmi <= 25 & gender == "m")
    { string weightclass = "super obese"; }

    Console.WriteLine("your bmi is " + bmi + " this means that you are " + weightclass);




    }
}
}

1 个答案:

答案 0 :(得分:1)

您必须将function redirect(){ window.location.href = "http://stackoverflow.com"; } - 变量的声明移到任何weightclass之外 - 阻止:

else

出现问题是因为每个变量都绑定到声明它的范围。当您在float bmi = ((weighnum) / ((heightnum) * (heightnum)) * 703); string weightclass = null; if (bmi < 17.5 & gender == "f") { weightclass = "anorexic"; } else if (bmi > 17.5 & bmi < 19.1 & gender == "f") ... - 块中声明一个时,您无法访问该特定范围。 Further information on scopes can be found here