c++基础语法:4、数据类型【2】
实型(浮点型)
作用:用于表示小数
浮点型分为两种:
- 单精度float
- 双精度double
两者的区分在于表示的有效数字范围不同
#include <iostream> using namespace std; int main() { // float float a = 5.6; cout << a << endl; // double double b = 5.6; cout << b << endl; //科学计数法表示 float d = 3e2; //代表 3 * 10 ^ 2 cout << d << endl; return 0; }
字符型
作用:字符型变量用于显示单个字符
语法:char c = "a";
在显示字符型变量时,用单引号键字符括起来,不要用双引号 单引号内只能有一个字符,不可以是字符串
bool类型占一个字节大小
-
C++和C中字符型变量只占用1个字节 字符型变量并不是把字符本身放到内存中存储,而是将对应的ASCII编码放到存储单元 #include <iostream> using namespace std; int main() { // 字符型 char d = D; cout << d << endl; cout << (int)d << endl; // 字符型对应ASCII编码 /* char d = "D"; 创建字符型变量时候,要用单引号 char d = hello; 创建字符型变量时候,单引号内只能有一个数值 */ system("pause"); return 0; } 转义字符 作用:用于表示一些不能显示出来的ASCII字符 常用的转义字符有://、/t、/n #include <iostream> using namespace std; int main() { // 换行符
cout << "Hello World
"; cout <<"Hello World" << endl; // 反斜杆 \ cout << "\" << endl; // 水平制表符 可以整齐输出数据 cout << "Hello World"; system("pause"); return 0; } C++风格字符串:string 变量名 = "字符串值" #include <iostream> #include <string> // 用C++风格字符串的时候,要包含这个头文件 using namespace std; int main() { // 包含一个头文件 string a = "hello world"; cout << a <<endl; cout << sizeof(a) << endl; // 40 system("pause"); return 0; } 布尔数据类型 bool 作用:布尔数据类型代表真或假的值 bool类型只有两个值 true:真(本质是1) false:假(本质是0) #include <iostream> #include <string> // 用C++风格字符串的时候,要包含这个头文件 using namespace std; int main() { // 创建bool数据类型 bool flag = true; // true代表真 cout << flag << endl; // 本质上,1代表真的值,0代表假的值 // 查看bool类型占用的内存空间 cout << flag << endl; system("pause"); return 0; }