我剛剛學習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);
}
}
}
當您提出這些問題時,請嘗試儘可能使錯誤文本具體。你應該得到更像「名稱」variablename「在當前上下文中不存在」的東西,越界意味着你在索引數組時遇到了錯誤。 –
您需要找到一種更好地組織代碼的方法,因爲不清楚是否所有輸入組合都由if語句處理。它看起來像不是:沒有if語句觸發器的組合,所以* weightclass *沒有被賦值。至少可以防止這種情況的一種方法是創建* weightclass *,並在代碼頂部爲它指定一個值,如*「unknown」*。這樣你會立即看到輸入的數值組合在問題中滑動。 –