数据类型作用:给变量分派合适内存空间
(空间不同,取值范围不同)
一、整型变量
short (2字节)取值范围:-32768~32767
int (4字节)
long (4 or 8字节) windows 4, Linux 8 byte
long long (8字节)
二、sizeof关键字
作用:统计数据类型所占内存大小
sizeof(数据类型 or 变量)
// short num1 = 10;
cout << "short所占内存空间大小:" << sizeof(num1) << endl;
cout << "short所占内存空间大小:" << sizeof(short) << endl;
三、实型(浮点型)
1.实型:表示小数
区别:表示有效数字范围不同
单精度:float (4字节)7位有效数字
双精度:double (8字节)15~16位有效数字
// float f1=3.14f (明现告知单精度)
(默认情况,输出小数点后5位有效数字)
2.科学计数法
float f1=3e2 (3* 10^2)
float f2=3e-2 (3* 0.1^2)
四、字符型
作用:显示单个字符
// char ch1='u';
char (1字节)
字符型变量:把对应的ASCII代码值放到存储单元中
char ch1 = 'b';
cout << "ch1=" << ch1 << endl;
cout << "ch1c存放ASCII代码值:" << (int)ch1 << endl;
// ch1=b;
ch2里面存放的ASCII代码值: 99;
char ch2 = 99;
cout << "ch2=" << ch2 << endl;
cout << "ch2里面存放的ASCII代码值:"<<(int)ch2 << endl;
// ch2=c;
ch2里面存放的ASCII代码值: 99;
五、转义字符
转义字符:表示不能明显显示出来的字符
\n 换行
\\ 输出\
\t 8个空格
cout << "HelloWord\n" << endl;
cout<<"HelloWord\\\\"<<endl;
cout << "aaaa\tHelloWord" << endl;
cout << "aa\tHelloWord" << endl;
cout << "aaaaaaa\tHelloWord" << endl;
输出如下:
六、字符串型
1. c风格
char str1[] = "hello word";
cout << str1 << endl;
2. c++风格
string str2 = "new hello word";
cout << str2 << endl;
七、bool类型
bool类型的值:
true 1
false 0
bool (1字节)
八、数据输入
1. 整型
int d = 10;
cout << "请输入整型数据d的值:";
cin >> d;
cout << "d=" << d << endl;
2. 浮点型
float f = 10.0f;
cout << "请输入浮点型f的值:";
cin >> f;
cout << "f=" << f << endl;
3. 字符型 (只能输入字母数字)
char ch = 'a';
cout << "请输入字符型ch的值:";
cin >> ch;
cout << "ch=" << ch << endl;
4. 字符串 (可-以输入有汉字)
string str = "hello word";
cout << "请输入str的值:";
cin >> str;
cout << "str=" << str << endl;
5. bool类型 (非0的值都代表1)
bool flag = false;
cout << "请输入bool类型的值:";
cin >> flag;
cout << "flag=" << flag<< endl;