gpt4 book ai didi

c++ - 在 If 语句中分配变量 [C++]

转载 作者:行者123 更新时间:2023-11-27 23:54:30 26 4
gpt4 key购买 nike

如果一个变量等于另一个值,我正在尝试分配一个变量。这是我的问题的简化版本:

#include <iostream>
using namespace std;

int main()
{
int a = 5;
int b;

cout << "A is this value (before if): " << a << endl;
cout << "B is this value (before if): " << b << endl;


if (a==5)
{
cout << "A equals five" << endl;
int b = 6;
cout << "B is this value (if stmt): " << b << endl;
}

cout << "B is this value (outside): " << b << endl;

return 0;

}

输出如下:

A is this value (before if):  5
B is this value (before if): 0
A equals five
B is this value (if stmt): 6
B is this value (outside): 0

为什么变量“b”在离开 if 语句后不保持分配为 6?有没有更好的方法来分配它?在我的实际代码中,我将五个变量与 a 进行比较。

最佳答案

您在 if block 中声明了一个新变量。用赋值替换变量声明。

此外,您应该初始化原始的b 变量。打印它的值而不初始化它会导致未定义的行为。

#include <iostream>
using namespace std;

int main()
{
int a = 5;
int b = 0;

cout << "A is this value (before if): " << a << endl;
cout << "B is this value (before if): " << b << endl;

if (a==5)
{
cout << "A equals five" << endl;
b = 6;
cout << "B is this value (if stmt): " << b << endl;
}

cout << "B is this value (outside): " << b << endl;
return 0;
}

关于c++ - 在 If 语句中分配变量 [C++],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43665900/

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