关键字sizeof、数据类型
sizeof关键字
用来计算数据类型所占空间的大小
1 #includesizeof关键字2 using namespace std; 3 4 int main() 5 { 6 //sizeof(数据类型); 计算数据类型所占的空间大小 7 8 cout << "short类型占" << sizeof(short) << endl; 9 cout << "int类型占:" << sizeof(int) << endl; 10 cout << "long类型占" << sizeof(long) << endl; 11 cout << "long long类型占" << sizeof(long long) << endl; 12 13 14 system("pause"); 15 return 0; 16 }
数据类型
1 浮点型
浮点型分为单精度和双精度
单精度为float 双精度为double
单精度可以保留7位有效数字
双精度可以保留15~16位有效数字
值得一提得的是,常规情况C++中不论哪种类型都只能保留6位有效数字,超出会用科学计数法表示
1 #include浮点型2 using namespace std; 3 4 int main() 5 { 6 // 单精度 float 7位有效数字 7 float Pai_1 = 3.14f; //单精度要加f,不然会被判断为双精度 8 9 // 双精度 double 15~16位有效数字 10 double Pai_2 = 3.14; 11 12 cout << "单精度:" << Pai_1 << "\n双精度:" << Pai_2 << endl; 13 14 //科学计数法 15 float text_1 = 3e2; //e代表10 3e2就是 3*10^2 16 float text_2 = 3e-2; //e-代表0.1 3e-2就是 3*0.1^2 17 18 cout << text_1 << "\n" << text_2 << endl; 19 20 //c++中不管单双精度,小数只能保留6位有效数字,超过会用科学计数法表示 21 22 system("pause"); 23 return 0; 24 }
2 字符型
字符型为char,占用内存为1
字符型要用单引号进行定义
1 #include字符型2 using namespace std; 3 4 int main() 5 { 6 //1 字符型变量创建方式 7 char text_1 = 'a'; 8 //2 字符型变量占内存大小为1 9 cout << "占内存大小:" << sizeof(char) << endl; 10 //3 字符型变量对应的ASCII码值 11 cout << (int)text_1 << endl; 12 13 system("pause"); 14 return 0; 15 }
3 字符串
字符串表达有两种形式
分别为c风格和C++风格
C风格依然使用char,C++风格则使用string
C风格注意事项:1 变量名后要加[]
2 要用双引号
C++风格注意事项:要定义一个头文件 #include
1 #include字符串型2 #include <string> 3 using namespace std; 4 5 int main() 6 { 7 //C风格字符串 8 //注意事项1:char后要加[] 9 //注意事项2:要用双引号 10 char str1[] = "helloworld"; 11 cout << str1 << endl; 12 13 //C++风格字符串 14 //注意事项:要包含一个头文件 #include 15 string str2 = "helloworld"; 16 cout << str2 << endl; 17 18 system("pause"); 19 return 0; 20 }
4 布尔类型
布尔类型为bool,所占内存为1
true为真,表示为1
false为假,表示为0
1 #include布尔类型2 #include <string> 3 using namespace std; 4 5 int main6() 6 { 7 //创建bool类型 1真 0假 8 bool test = true; 9 cout << test << endl; 10 11 test = false; 12 cout << test << endl; 13 14 //bool所占内存为1 15 cout << sizeof(bool) << endl; 16 17 system("pause"); 18 return 0; 19 }
转义字符
常用的转义字符
| \n | 换行符 | 用于换行 |
| \t | 水平制表符 | 长度为8,制表符后面的字母有对齐的效果 |
| \\ | 输出斜杠 | 想输出1个反斜杠,要用2个反斜杠 |
1 #include转义字符2 using namespace std; 3 4 int main() 5 { 6 //换行符 7 cout << "hello\nworld" << endl; 8 9 //水平制表符 \t长度为8 10 //用处:制表符后面的字母有对齐的效果 11 cout << "aaa\thello" << endl; 12 cout << "aaaaa\thello" << endl; 13 cout << "a\thello" << endl; 14 cout << "aaaa\thello" << endl; 15 16 //反斜杠 想打印1个反斜杠,要用2个反斜杠 17 cout << "\\" << endl; 18 19 system("pause"); 20 return 0; 21 }
数据的输入
语法为: cin>>
使用户根据需求输入指定类型的数据
1 #include数据的输入2 #include <string> 3 using namespace std; 4 5 int main() 6 { 7 // ctrl+k+c 全部注释 8 9 //数据的输入 10 int a; 11 cout << "请赋值:" << endl; 12 cin >> a; //输入 13 cout << a << endl; 14 15 system("pause"); 16 return 0; 17 }