我的C ++代码永远不会通过else语句执行

时间:2017-09-09 08:16:19

标签: c++ if-statement

刚刚开始。 Xcode告诉我这个"代码永远不会在else语句的第一行执行,我也不知道如何处理它。

我试图这样做,如果用户的输入不是switch语句中的四个选项之一,则默认为第三个选项。请帮忙。

int lengthoption;
std::cout << "Please select an option for the length of your loan based on the following options: " << std::endl;
std::cout << "1. 3 years" <<std::endl;
std::cout << "2. 4 years" <<std::endl;
std::cout << "3. 5 years" <<std::endl;
std::cout << "4. 6 years" <<std::endl;
std::cin >> lengthoption;


double NumberofPayments;
if (lengthoption == 1 || 2 || 3 || 4)
{
    switch (lengthoption)
    {
        case 1:
            NumberofPayments = 36;
            std::cout << "You chose a 3 year loan with a total of " << NumberofPayments << " monthly payments." << std::endl;
            break;
        case 2:
            NumberofPayments = 48;
            std::cout << "You chose a 4 year loan with a total of " << NumberofPayments << " monthly payments." << std::endl;
            break;
        case 3:
            NumberofPayments = 60;
            std::cout << "You chose a 5 year loan with a total of " << NumberofPayments << " monthly payments." << std::endl;
            break;
        case 4:
            NumberofPayments = 72;
            std::cout << "You chose a 6 year loan with a total of " << NumberofPayments << " monthly payments." << std::endl;
    }
}

else
{
    ***NumberofPayments = 60;***
    std::cout << "You chose a 5 year loan with a total of " << NumberofPayments << " monthly payments." << std::endl;
}

1 个答案:

答案 0 :(得分:2)

if (lengthoption == 1 || 2 || 3 || 4)

2计算结果为true,因此条件始终为真。

你必须在每个||之间放置完整的布尔表达式:

if (lengthoption == 1 || 
    lengthoption == 2 || 
    lengthoption == 3 || 
    lengthoption == 4)

或者

if (lengthoption >= 1 && lengthoption <= 4)