简体   繁体   English

If, Else-If 逻辑检查

[英]If, Else-If Logic Check

I have someone telling me that the logic in the if else-if below is not correct because I should have included an upper and lower limit in every else-if because when you enter a 6 more than one else-if is true;有人告诉我,下面 if else-if 中的逻辑不正确,因为我应该在每个 else-if 中都包含一个上限和下限,因为当您输入 6 多于一个 else-if 时,如果是真的; I thought that since the else-if breaks out when finding a true, that this was just as good.我认为既然 else-if 在找到一个 true 时会爆发,这同样好。 What do think?怎么想?

int hoursOfSleep = 9;

if (hoursOfSleep >= 10 )
{
    Console.WriteLine("Wow! That's a lot of sleep!");
}
else if (hoursOfSleep > 8 )
{
    Console.WriteLine("You should be pretty rested.");
}
else if (hoursOfSleep > 5)
{
    Console.WriteLine("That's not bad.");
}
else if (hoursOfSleep > 4)
{
    Console.WriteLine("Bummer.");
}
else
{
    Console.WriteLine("Oh man, get some sleep!");
}

You right.你说得对。

The program will do either the task inside the if block if the test expression is true or the task inside the else if the test expression is false.如果测试表达式为真程序执行 if 块内的任务,如果测试表达式为假,则执行 else 内的任务。

When using else if, it will do the same thing, check the expression in the if and continue to the else if it's false.当使用 else if 时,它会做同样的事情,检查 if 中的表达式,如果为 false,则继续执行 else。

Only one hit is possible in if-else condition, if the test expression will remain false till the end then the last else will be execute.在 if-else 条件下只有一次命中是可能的,如果测试表达式将保持为假直到结束,那么最后一个 else 将被执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM