如何在C ++中改变Bool值?

时间:2017-09-13 15:52:51

标签: boolean

所以我一直试图找出一段时间的bool功能。 我试图在输入特定值之后这样做,bool将变为真或假。

#include <iostream>

using namespace std;

int a;
bool dead;

void Life() {
    if (dead == true) {
        cout << "You ded.";
    }
    else {
        cout << "You not ded.";
    }
}

int main()
{
    cin >> a;
    if (a == 10)
    {
        bool dead = true;
    }
    Life();
    return 0;
}

这就是我现在所拥有的,但它没有改变bool的价值。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

你在main的if块中重新声明变量'dead'。所以现在你有两个'bool dead',一个全局的,一个在main的if块中的本地一个。语句'bool dead = true'设置本地语句,但函数'Life()'使用全局语句。只需从后者中移除'bool',您将始终使用全局的那个。

#include <iostream>

using namespace std;

int a;
bool dead;

void Life() {
    if (dead == true) {
        cout << "You ded.";
    }
    else {
        cout << "You not ded.";
    }
}

int main()
{
    cin >> a;
    if (a == 10)
    {
        dead = true;
    }
    Life();
    return 0;
}

答案 1 :(得分:0)

有两个变量称为死亡。   - 全球化   - 本地的生命周期是if块

您只在if块中设置局部变量。所以你不要改变全局变量。删除if块内的类型,程序可以按预期运行。并且不要忘记初始化全局死变量。根据操作系统和状态,您的全局变量可能以真值开头。