【问题标题】:If statements with multiple variables具有多个变量的 if 语句
【发布时间】:2019-08-29 04:41:46
【问题描述】:

我正在尝试将if 语句与多个比较操作一起使用,但day 变量在我的if 语句中不起作用。

这是我的代码:

int day;
string rain;

cout << "What day of the week is it?" << endl;
cin >> day;

while (0 < day < 8)
{
    cout << "Is it raining? Please type 'yes' or 'no' " << endl;
    cin >> rain;

    if ((0 < day < 3) && (rain == "yes"))
    cout << "Read in bed" << endl;

    else if ((0 < day < 3) && (rain == "no"))
        cout << "Go out and play!" << endl;

    else if ((2 < day < 8) && (rain == "yes"))
        cout << "Take an umbrella!" << endl;
    else
        cout << "No umberella needed" << endl;

    cout << "What day of the week is it?" << endl;
    cin >> day;
}

cout << "Invalid day sorry" << endl;

获取Read in bedgo out and play,但从不获取Take an umbrella

如果我输入day = 9,我的代码也可以工作。

【问题讨论】:

  • 有比这更好的编码实践......尝试使用Invalid day sorry 作为中断语句的无限循环。并且可以安全地构建程序以到达所有端点
  • 如果一个答案解决了您的问题,那么请考虑支持并标记它已解决。给贡献者一些功劳:)
  • 这并不能解决问题,但您不需要在各个比较周围加上括号。 if(0 &lt; day &amp;&amp; day &lt; 3 &amp;&amp; rain == "yes")if ((0 &lt; day) &amp;&amp; (day &lt; 3) &amp;&amp; (rain == "yes")) 意思相同。对于有经验的程序员来说,第二个更难阅读,因为你必须停下来弄清楚括号实际上并没有做任何事情。

标签: c++ if-statement comparison-operators


【解决方案1】:

您需要使用逻辑 AND (&amp;&amp;) 运算符更正涉及 day 变量的条件。

例如,0 &lt; day &lt; 8 表示您正在针对两个不同的值测试 day,即 day 是否在此范围之间。因此,在您的情况下,应使用逻辑运算符和 &amp;&amp; 组合这两个比较。因此,应该是这样的:

day > 0 && day < 8

day 进行比较的其他条件也是如此。


有关逻辑运算符的更多详细信息,请参阅参考: https://en.cppreference.com/w/cpp/language/operator_logical

【讨论】:

    【解决方案2】:

    使用7 &lt; day &amp;&amp; day &lt; 0

    一旦你写了0 &lt; day &lt; 3 C++ 评估其中之一,然后比较变成boolean

    我觉得对您的代码更好的方法:我可以到达所有端点

        while (true) {
    
            cout << "What day of the week is it?" << endl;
            cin >> day;
    
            if (7 < day &&  day < 0 ){
                cout << "Invalid day sorry" << endl;
                break;
            }
    
            cout << "Is it raining? Please type 'yes' or 'no' " << endl;
            cin >> rain;
    
            if (0 < day && day < 3) {
                if (rain == "yes") {
                    cout << "Read in bed" << endl;
                } else {
                    cout << "Go out and play!" << endl;
                }
            } else {
                if (rain == "yes")
                    cout << "Take an umbrella!" << endl;
                else
                    cout << "No umberella needed" << endl;
            }
    
        }
    

    【讨论】:

      【解决方案3】:

      这与if语句和多个变量无关,您的0 &lt; day &lt; 3实际上应该读作0 &lt; day &amp;&amp; day &lt; 3。顺便说一句,你不需要在同一个 if 语句的每个分支中测试它,它不太可能改变。

      【讨论】:

      • 非常感谢,仍在努力了解基础知识
      【解决方案4】:

      这不是 C++ 的工作方式:

      0 < day < 3
      

      你必须改变它

      day > 0 && day < 3
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-02
        • 2014-10-20
        相关资源
        最近更新 更多