打工人学C++系列——2.C++中的数据类型

C++中创建变量常量时,必须指定数据类型,不然无法分配内存。

2.1 整型

1.short(短整型):2字节;取值范围:-215~215-1
2.int(整型):4字节;取值范围:-231~231-1
3.long(长整型):windows4字节,linux32位4字节,64位8字节
4.long long(长长整型):8字节;取值范围:-263~263-1
超出取值范围,就会反到负值的极限。int最常用。
所占内存:Short<int<=long<=long long

    short num1 = 32769;
	int num2 = 10;
	long num3 = 10;
	long long num4 = 10;
	cout << "num1 = " << num1 << endl;
	cout << "num2 = " << num2 << endl;
	cout << "num3 = " << num3 << endl;
	cout << "num4 = " << num4 << endl;

2.2 sizeof关键字

1.作用:统计数据类型占内存大小
2.语法:sizeof(数据类型或者变量)

    //4.sizeof查询作占内存
	cout << "int占用内存:" << sizeof(int) << endl;
	cout << "num1所占内存:" << sizeof(num1) << endl;

2.3 实型(浮点型)

1.单精度float:4字节,7位有效数字
2.双精度double:8字节,15~16位有效数字
PS:
1.创建变量时,编译器默认双精度,在后面加个f就是指定了单精度。例如:float f1 = 3.14f;
2.C++中小数默认输出显示6位有效数字,不管是单精度还是双精度;
3.可以用科学计数法表示小数:3e2表示3*102;3e-2表示3*0.12

    //5.浮点型,单精度双精度
	float f1 = 3.1415926f;
	cout << "f1 = " << f1 << endl;
	double d1 = 3.1415926;
	cout << "d1 = " << d1 << endl;
	cout << "double所占空间:" << sizeof(double) << endl;
	//6.科学计数法
	float f2 = 3e2;
	cout << "f2 = " << f2 << endl;
	float f3 = 3e-2;
	cout << "f3 = " << f3 << endl;

2.4 字符型

1.作用:用于显示单个字符
2.语法:char ch = ‘a’
3.注意:单引号括起来,只能有一个字符
4.占用一个字节,并不是把字符本身放在内存,而是将对应的ASCII编码放进去。查看ascii码是啥,强制转换成int,cout即可。(int)ch

    //7.字符型
	char ch = 'b';
	cout << ch << endl;
	cout << (int)ch << endl;

2.5 转义字符

1.作用:用于不能显示出来的ASCII码
2.常用转义字符:
换行:\n
水平制表(跳到下一个TAB位置):\t ;用于整齐的输出数据;\t一共占了8个空间;
反斜线:\

    //8.转义字符
	cout << "hello world\n";
	cout << "\\\n";
	cout << "aaa\thello" << endl;
	cout << "aa\thello" << endl;
	cout << "aaaaaaaaaaa\thello" << endl;
	cout << "aaaaaaaaa\thello" << endl;

2.6 字符串

1.c语言风格:char 变量名[] = “字符串值”;双引号,中括号
2.c++风格:string 变量名 = “字符串值”
需要加一个头文件 #include

    //9.字符串
	char str1[] = "hello world1";
	cout << "STR1 = " << str1 << endl;
	string str2 = "hello world2";
	cout << "STR2 = " << str2 << endl;

2.7 布尔类型

1.作用:代表真假值,只要非0的值都代表真
2.true真,本质是1
false假,本质是0
占1字节

    //bool类型
	bool flag = false;
	cout << flag << endl;
	flag = true;
	cout << flag << endl;
	cout << sizeof(flag) << endl;

2.8 数据输入

从键盘获取:cin >> 变量

    //数据输入
	int b = 0;
	cout << "请给整型变量b赋值:" << endl;
	cin >> b;
	cout << "整型b = " << b << endl;
	string str3 = "hello";
	cout << "给STR3赋值:" << endl;
	cin >> str3;
	cout << "str3为:" << str3 << endl;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

brave_555

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值