当前位置:网站首页>52.【bool类型输入任何非0数值不为1的版本原因】
52.【bool类型输入任何非0数值不为1的版本原因】
2022-08-02 07:34:00 【李在奋斗……】
【visual studio 2022版】

【即bool类型不赋初值】
#include <iostream>
using namespace std;
int main()
{
bool x;
cout << "请您手动输入bool的值为:" << endl;
cin >> x;
cout << "结果为:" << x << endl;
return 0;
}

==================== 
【即bool赋初值】
#include <iostream>
using namespace std;
int main()
{
bool x=false;
cout << "请您手动输入bool的值为:" << endl;
cin >> x;
cout << "结果为:" <<boolalpha<< x << endl;
return 0;
}

==========================
【visual studio 2015版】

【即bool类型不赋初值】
#include <iostream>
using namespace std;
int main()
{
bool x;
cout << "请您手动输入bool的值为:" << endl;
cin >> x;
cout << "结果为:" << x << endl;
return 0;
}

====================
【当bool赋初值的时候(会变false)】
#include <iostream>
using namespace std;
int main()
{
bool x=false;
cout << "请您手动输入bool的值为:" << endl;
cin >> x;
cout << "结果为:" <<boolalpha<< x << endl;
return 0;
}

为什么会变成这样?
因为当bool类型变量通过cin赋值时,如果输入”非0非1“,变量值不改变。也就是bool类型变量通过cin进行赋值只能键入0或者1,其他无效。
怎么更改呢?
一般通过设置中间量判断,再对bool变量进行间接赋值。无论对x有没有定义,通过int类型变量a来强制赋值bool类型变量x,有效解决上边出现的问题。
====================
【强制赋值】
#include <iostream>
using namespace std;
int main()
{
bool x=false;
cout << "请您手动输入bool的值为:" << endl;
int a;
cin >> a;
x = a;
cout << "结果为:" <<boolalpha<< x << endl;
return 0;
}

边栏推荐
- Conditional constructor ~wapper
- How to export multiple query results at once in SQL server 2014?
- uni.navigateBack 中的坑
- 【CV】OpenVINO installation tutorial
- WebGPU 导入[2] - 核心概念与重要机制解读
- DeadLock的可视化分析
- MySQL事务隔离级别详解
- 小说里的编程 【连载之二十三】元宇宙里月亮弯弯
- Transimpedance amplifier
- Aided by training and learning by battle | The new version of the Offensive and Defense World Platform is officially launched!
猜你喜欢

2022-7-31 12点 程序爱生活 恒指底背离中,有1-2周反弹希望

MySQL - Index Optimization and Query Optimization

MySQL优化:从十几秒优化到三百毫秒

有点奇怪!访问目的网址,主机能容器却不行

HCIP 第十一天

暂未找到具体原因但解决了的bug

Understand Chisel language. 31. Chisel advanced communication state machine (3) - Ready-Valid interface: definition, timing and implementation in Chisel

Compact格式下MySQL的数据如何存储到磁盘

redis-advanced

Hack The Box - File Transfers Module详细讲解中文教程
随机推荐
MySQL-执行流程+缓存+存储引擎
传递泛型给JSX元素
MySQL之创建表的基本操作
HCIP 第六天
spark read local file
mysql如何从某一行检索到最后
Introduction to mysql operation (4) ----- data sorting (ascending, descending, multi-field sorting)
MySQL database design specification
MySQL优化之慢日志查询
7.联合索引(最左前缀原则)
通过建立新的SaaS业务来推动增长的六种方法
机器学习笔记--数学库
Transimpedance amplifier
18、优化网站性能
Inverter insulation detection detection function and software implementation
[Unity3D] Beginner Encryption Skills (Anti-Cracking)
playwright 爬虫使用
Xilinx Constraint Study Notes - Timing Constraints
MySQL-Execution Process + Cache + Storage Engine
RIP综合实验