為什么第 17 行永遠不會被執行。我相信它(if else 陳述句)一旦滿足第一個條件就會終止。如果是這樣,如何解決這個問題。有沒有辦法檢查所有條件?
#include <iostream>
/*
Why does the third if else statement never gets executed. I believe that
it(if else statement) gets terminated as soon as it meets the first
condition. If so, how to solve this problem. Are there any way to check
all of the conditions?
*/
int main() //This check if you can drive a car or not
{
int age;
std::cout << "Enter your age: ";
std::cin >> age;
if (age >= 18)
std::cout << "You can drive.\n";
else if (age < 18)
std::cout << "You have to be 18 to drive.\n";
else if (age >= 80) // 80 and above should not drive
std::cout << "You are too old to drive\n";
return 0;
}
uj5u.com熱心網友回復:
您的第一個測驗是針對age >= 18. 上述任何年齡都將通過,甚至不會檢查18任何后續測驗。else if如果您希望它按預期作業,請確保先進行測驗age >= 80,因此下一個測驗僅將80以下的組分開,例如:
if (age >= 80)
std::cout << "You are too old to drive\n";
else if (age < 18)
std::cout << "You have to be 18 to drive.\n";
else // Don't need a final if check; the previous two checks ensure if you get here, the age is between 18 and 79 inclusive
std::cout << "You can drive.\n";
uj5u.com熱心網友回復:
它永遠不會達到,age >= 80因為一個大的值總是能滿足的要求,age >= 18并else告訴它只選擇一個選項。
您可以先檢查超過 80 個條件以確保找到它。
if (age >= 80) // 80 and above should not drive
std::cout << "You are too old to drive\n";
else if (age >= 18)
std::cout << "You can drive.\n";
else if (age < 18)
std::cout << "You have to be 18 to drive.\n";
或者您可以在第一個 if 陳述句中添加一個條件,這樣它就不會適用于超過 80 個。
if (age >= 18 && age < 80)
std::cout << "You can drive.\n";
else if (age < 18)
std::cout << "You have to be 18 to drive.\n";
else if (age >= 80) // 80 and above should not drive
std::cout << "You are too old to drive\n";
uj5u.com熱心網友回復:
如果age >= 18為假,age < 18則為真。
所以,無論如何age,第三個if永遠都達不到。
uj5u.com熱心網友回復:
如果您的輸入年齡已經與第一個 if 陳述句進行比較,它將不會通過其余的 if 陳述句。因此,如果您的年齡 > 18,if 陳述句將不會在第 17 行檢查它是否 >= 80。
因此,您可以在第一個 if 陳述句中執行另一個 if 陳述句,也可以在第一個 if 陳述句中添加更多條件。
if (age >= 18 && age < 80){
std::cout << "You can drive.\n";
}
或者,您可以執行以下操作:
if (age >= 18){
if(age >= 80){
std::cout << "You are too old to drive. \n";
}
else{
std::cout << "You can drive.\n";
}
}
您可以洗掉第三個 if 陳述句,因為它永遠不會被執行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/441473.html
標籤:C
上一篇:c 參考二維陣列函式的問題
下一篇:為什么加載矢量時有這么多重復項
