【问题标题】:Suggestions for comparing two booleans in an if-statement in c++在 C++ 中的 if 语句中比较两个布尔值的建议
【发布时间】:2017-11-16 02:48:47
【问题描述】:

我编写的一些代码有问题。

我正在用 c++ 编写,我正在尝试设置 3 个字符串,所有这些字符串都是“关闭”的。我还尝试在程序开始时将 2 个布尔值设置为 false。所有这些起始代码都有效。

我想设置一个 if 语句,这样如果布尔值同时是true,那么所有的字符串都会变成“on”,然后程序会打印一个输出说它们是在。

我在网上查过,但找不到答案,所以如果您有任何想法,我非常感谢您的帮助。

谢谢!

以下是参考代码:

//imports the required utilities for the program
#include <iostream>
#include <string>
using namespace std;
//sets up the main method 
    int main()
    {
//declares and assigns all variables needed for program
        string light1 = "off";
        string light2 = "off";
        string electricity = "off";
        bool power(false);
        bool pressure(true);
//prints the outcome to indicate that the electricity is off to begin with
        std::cout << ("The Electricity is " + electricity +", Light #1 is "+ 
light1 +" and Light #2 is "+ light2 +".");
//introduces if statement to turn on electricity in lights
        if ((power) && (pressure))
        {
            string light1 = "on";
            string light2 = "on";
            string electricity = "on"; 
        }
//prints the new outcome to indicate if the electricity is on
        cout << "\n";
        std::cout << ("The Electricity is " + electricity +", Light #1 is "+ 
light1 +" and Light #2 is "+ light2 +"."); 
     }

【问题讨论】:

  • 问题不清楚。我认为你的比较很好
  • "我还试图在程序开始时将 2 个布尔值设置为 false。" - pressure 在程序开始时声明为 true
  • 代替cout &lt;&lt; (a + b + c),使用cout &lt;&lt; a &lt;&lt; b &lt;&lt; c。在这种情况下它成功了,但将来可能会出现问题
  • 不要放那么多cmets来解释你做了什么,尤其只是告诉读者你初始化了变量。如果一段代码做了一些值得命名/描述的事情,请将其放入函数中,命名并调用 that。这样一来,您的代码预执行的操作就写在那里,而不是编译器(和人们)忽略的注释中。
  • @JedaiCoder &amp;&amp; 是一个运算符,它不比较两个操作数。它无条件地评估第一个操作数,但在第二个操作数上短路

标签: c++ if-statement boolean boolean-expression


【解决方案1】:

您正在声明三个仅存在于该 if 语句范围内的新字符串变量。删除数据类型以将值分配给 if 语句之外的字符串,就像这样

if ((power) && (pressure))
{
    light1 = "on";
    light2 = "on";
    electricity = "on";
}

【讨论】:

  • 非常感谢,它成功了,现在程序运行良好!再次感谢!
【解决方案2】:

在下面修复。不要在 if 语句中重新声明变量,C++ 有一个范围的概念,更多信息请看这里http://en.cppreference.com/w/cpp/language/scope。在实现文件的顶部添加 using namespace std; 也被认为非常糟糕(对于像你这样的小例子很好,但要小心未来)

#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

int main()
{
    string light1 = "off";
    string light2 = "off";
    string electricity = "off";
    bool power(false);
    bool pressure(true);

    cout << ("The Electricity is " + electricity +", Light #1 is "
            + light1 +" and Light #2 is "+ light2 +".") << endl;

    power = pressure = true;
    if ((power) && (pressure))
    {
        light1 = "on";
        light2 = "on";
        electricity = "on";
    }

    cout << ("The Electricity is " + electricity +", Light #1 is "
            + light1 +" and Light #2 is "+ light2 +".") << endl;
}

【讨论】:

    猜你喜欢
    • 2017-10-01
    • 2018-02-01
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 2013-09-25
    • 2011-07-16
    • 2018-05-16
    相关资源
    最近更新 更多