布尔类型赋值问题C++

来源:百度知道 编辑:UC知道 时间:2024/06/18 17:50:30
#include<iostream>
using namespace std;
int main()
{int x,y;
bool a=false;
bool b=false;
bool c=false;
cout<<"Enter 2integers:\n";
cin>>x>>y;

if(x>y)
{bool a=true;
bool b=false;
bool c=false;
}
else if(x<y)
{bool a=false;
bool b=false;
bool c=true;
}
else
{bool a=false;
bool b=true;
bool c=false;
}
cout<<"x_isgreaterthan_y is "<<a<<endl<<"x_isequalto_y is"<<b<<endl<< "x_islessthan_y is "<<c<<endl;
return 0;
}
该程序不论怎么输入输出为什么总是0,0,0?

是作用域的问题
#include<iostream>
using namespace std;
int main()
{int x,y;
bool a=false;
bool b=false;
bool c=false;
cout<<"Enter 2integers:\n";
cin>>x>>y;

if(x>y)
{ a=true;
b=false;
c=false;
}
else if(x<y)
{ a=false;
b=false;
c=true;
}
else
{ a=false;
b=true;
c=false;
}
cout<<"x_isgreaterthan_y is "<<a<<endl<<"x_isequalto_y is"<<b<<endl<< "x_islessthan_y is "<<c<<endl;
return 0;
}
你在if判断语句里面的变量加了bool类型.所以他是声明了新的局部变量.而自始直总都没有修改变量a,b,c.
所以你在最后输出的时候会是0.
以上是正确的代码.如果不懂我说的什么意思就
仔细分析我的代码和你的有什么不同吧.

bool 值直接输出就是 0或1
如果你想打印true/false需要这样
bool test=false;
cout << "test=" << test?"true":"false" <<endl;

像我这样就可以了~~~~~~!~!~!~!
<