【发布时间】: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 << (a + b + c),使用cout << a << b << c。在这种情况下它成功了,但将来可能会出现问题 -
不要放那么多cmets来解释你做了什么,尤其只是告诉读者你初始化了变量。如果一段代码做了一些值得命名/描述的事情,请将其放入函数中,命名并调用 that。这样一来,您的代码预执行的操作就写在那里,而不是编译器(和人们)忽略的注释中。
-
@JedaiCoder
&&是一个运算符,它不比较两个操作数。它无条件地评估第一个操作数,但在第二个操作数上短路
标签: c++ if-statement boolean boolean-expression