gpt4 book ai didi

c++ - 在 C++ 的 if 语句中比较两个 boolean 值的建议

转载 作者:行者123 更新时间:2023-11-28 01:47:16 27 4
gpt4 key购买 nike

我写的一些代码有问题。

我正在用 C++ 编写,我正在尝试设置 3 个字符串,所有字符串都处于“关闭”状态。我还试图在程序开始时将 2 个 boolean 值设置为 false。所有这些开始代码都有效。

我想设置一个 if 语句,这样如果 boolean 值同时为 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 +".");
}

最佳答案

您正在声明三个新的字符串变量,它们只存在于该 if 语句的范围内。删除数据类型以将值分配给 if 语句之外的字符串,如下所示

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

关于c++ - 在 C++ 的 if 语句中比较两个 boolean 值的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44536494/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com