我是c#的新手,在处理基本程序时我收到此错误(错误只有赋值,调用,递增,递减,等待和新对象表达式可以用作语句)并且无法弄清楚为什么它出现了。
if (pizzaDiameter >= 12 && pizzaDiameter < 16)// begin nested if statement
{
Console.WriteLine("A" + pizzaDiameter + "will yield 8 slices.");
}
else if (pizzaDiameter >= 16 && pizzaDiameter < 24)//Second pizza diameter range
{
Console.WriteLine("A" + pizzaDiameter + "will yield 12 slices.");
}
else if (pizzaDiameter >= 24 && pizzaDiameter < 30)
{
Console.WriteLine("A" + pizzaDiameter + "will yield 16 slices.");
}
else (pizzaDiameter >= 24 && pizzaDiameter <= 30)
{
Console.WriteLine("A" + pizzaDiameter + "will yield 24 slices.");
}
else // pizza diameter was not a whole number
{
Console.WriteLine("Pizza diameter must be between 12-36 inclusive.");// Error appears here.
}
else //pizza diameter must be between 12-36
{
Console.WriteLine("Pizza diameter must be a whole number.");
}
答案 0 :(得分:2)
您的控制结构出现了问题,即您只有一个if()
,但有三次else
。
此外,尝试考虑问题并且您会注意到您可以显着简化整个结构(并且还跳过许多检查):
if (pizzaDiameter < 12) // All diameters below 12 will use this branch.
Console.WriteLine("Your pizza seems to be too small.");
else if (pizzaDiameter < 16) // You don't have to ensure it's bigger than 12, since those smaller already picked the branch above.
Console.WriteLine("A diameter of " + pizzaDiameter + " will yield 8 slices");
else if (pizzaDiameter < 24) // Again you won't have to care for less than 16.
Console.WriteLine("A diameter of " + pizzaDiameter + " will yield 12 slices");
// ...
else
Console.WriteLine("Your pizza seems to be too big.");