C 语言基础二:数据类型
一. 字节与位数关系
| 单位 | 描述 | 换算关系 |
|---|
| 位(bit) | 计算机最小存储单位,只有0/1 | |
| 字节(Byte) | 8位组成一字节 | 1Byte = 8bit |
| 千字节(Byte) | 1024字节 | 1KB = 1024Byte |
| 兆字节(Byte) | 1024千字节 | 1MB = 1024KB |
二. 整数类型
| 数据类型 | 字节数 | 位数 | 取值范围 |
|---|
char | 1 | 8 | 有符号-128到127,无符号0-255 |
short | 2 | 16 | 有符号-32768到32767,无符号0-65535 |
int | 4 | 32 | 有符号 - 2,147,483,648 到 2,147,483,647 |
long | 4(32位系统)/8(64位系统) | 32/64 | 很大 |
long long | 8 | 64 | 更大 |
- 无符号整数
位数:n
取值范围:0 到 2ⁿ - 1
示例:unsigned char(8 位)的取值范围是 0 到 2⁸ - 1 = 255
- 有符号整数(补码表示
位数:n(最高位为符号位)
取值范围:-2ⁿ⁻¹ 到 2ⁿ⁻¹ - 1
示例:signed char(8 位)的取值范围是 -2⁷ = -128 到 2⁷ - 1 = 127
三. 浮点类型
| 数据类型 | 字节数 | 位数 | 精度范围 |
|---|
float | 4 | 32 | 6-7位有效数字 |
double | 8 | 64 | 15-16位有效数字 |
long double | 8/10/16 | 64/80/128 | 精度很高 |
四. 布尔类型(C99及以后版本)
#include <stdio.h>
#include <stdbool.h>
int main(void){
bool isReady = true;
bool isDid = false;
printf("isReady:%d\n",isReady);
printf("isReady:%s\n",isReady ? "true": "false");
return 0;
}
五. 空类型
六. 派生类型
- 数组
- 指针
- 结构体
- 联合体
- 枚举
enum WeakDay{
MON,
TRU,
WED
};
int main(void){
enum WeakDay today = TRU;
if(today == WED){
printf("yes");
}
return 0;
}
- 字符串
char c1 = 'c';
printf("c1:%c\n",c1);
char c2[] = "helloworld";
printf("c2:%s\n",c2);
七. 各种类型色输出
#include <stdio.h>
#include <stdbool.h>
int main(void){
bool isReady = true;
printf("isReady:%d\n",isReady);
printf("isReady:%s\n",isReady ? "true": "false");
printf("int: %zu 字节\n",sizeof(int));
short a1 = 1;
int a2 = 2;
long a3 = 3;
printf("a1:%hd\n",a1);
printf("a2:%d\n",a2);
printf("a3:%ld\n",a3);
float b1= 1.234567;
double b2= 1.234567;
printf("b1:%f\n",b1);
printf("b2:%.2lf\n",b2);
char c1 = 'c';
printf("c1:%c\n",c1);
char c2[] = "helloworld";
printf("c2:%s\n",c2);
return 0;
}
八. 强制类型转换
int a = 15
double b = (double)a
printf("a:%d\n",a)
printf("b:%lf\n",b)