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

标签 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;
}

最佳答案

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

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

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

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

或许

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

关于c++ - 我的 C++ 代码永远不会通过 else 语句执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46128602/

相关文章:

excel - 变量属于一个值范围

ruby-on-rails - 增加购物车数量 RoR

java - 检查字段是否为空

c++ - 用一种语言编写的代码如何被另一种语言调用

C++ If 在 for 循环中循环。限制

bash if 子句与 and or 组合

java - 如果移动了特定文件,如何读取它

c++ array[var][2] 作为类成员

c++ - 如何将 WT 小部件放入 PDF?

c++ - 程序状态的任何变化是否构成可观察到的行为?