我的C 代码永远不会超过其他语句

My C++ code will never be executed past the else statement

本文关键字:其他 语句 代码 永远 我的      更新时间:2023-10-16

刚从这里开始。Xcode告诉我,"代码永远不会在其他语句中的第一行上执行,我不知道该怎么做。

我正在尝试做到这一点,以便如果用户的输入不是开关语句中的四个选项,则默认为第三个选项。请帮助。

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;
}
if (lengthoption == 1 || 2 || 3 || 4)

2评估为true,因此条件始终是正确的。

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

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

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