文章主要记录C语言的学习笔记。
四、C语言的数据类型
C语言的数据类型主要包括四种类型:
1、基本类型:C语言的基本类型包括两种类型——整数类型和浮点类型。
2、void类型:void类型说明没有可用的值。
3、枚举类型:枚举类型是用来定义在程序中只能赋予其一定离散整数值的变量。
4、派生类型:派生类型包括:数组类型、结构体类型、共用体类型、指针类型和函数类型。
4.1 C语言基本数据类型
C语言的整数类型
下表列出了关于标准整数类型的存储大小和值范围的细节(不同操作系统位数的的存储大小有所区别):
类型 | 存储大小 | 值范围 |
---|---|---|
char | 1 字节 | -128 到 127 或 0 到 255 |
unsigned char | 1 字节 | 0 到 255 |
signed char | 1 字节 | -128 到 127 |
int | 2 或 4 字节 | -32,768 到 32,767 或 -2,147,483,648 到 2,147,483,647 |
unsigned int | 2 或 4 字节 | 0 到 65,535 或 0 到 4,294,967,295 |
short | 2 字节 | -32,768 到 32,767 |
unsigned short | 2 字节 | 0 到 65,535 |
long | 4 字节 | -2,147,483,648 到 2,147,483,647 |
unsigned long | 4 字节 | 0 到 4,294,967,295 |
我们可以使用 sizeof (type) 运算符来得到对象或类型的存储字节大小。
实例:获取不同类型的存储字节大小。
#include<string.h>
#include<stdio.h>
int main(void)
{
int A = 18;
printf("char 存储大小 : %lu \n", sizeof(char));
printf("unsigned char 存储大小 : %lu \n", sizeof(unsigned char));
printf("signed char 存储大小 : %lu \n", sizeof(signed char));
printf("int 存储大小 : %lu \n", sizeof(int));
printf("unsigned int 存储大小 : %lu \n", sizeof(unsigned int));
printf("short 存储大小 : %lu \n", sizeof(short));
printf("unsigned short 存储大小 : %lu \n", sizeof(unsigned short));
printf("long 存储大小 : %lu \n", sizeof(long));
printf("unsigned long 存储大小 : %lu \n", sizeof(unsigned long));
return 0;
}
C语言的浮点类型
下表列出了关于标准浮点类型的存储大小、值范围和精度的细节:
类型 | 存储大小 | 值范围 | 精度 |
---|---|---|---|
float | 4 字节 | 1.2E-38 到 3.4E+38 | 6 位有效位 |
double | 8 字节 | 2.3E-308 到 1.7E+308 | 15 位有效位 |
long double | 16 字节 | 3.4E-4932 到 1.1E+4932 | 19 位有效位 |
C语言的void类型
void 类型指定没有可用的值。它通常用于以下三种情况下:
序号 | 类型与描述 |
---|---|
1 | 函数返回为空 C 中有各种函数都不返回值,或者您可以说它们返回空。不返回值的函数的返回类型为空。例如 void exit (int status); |
2 | 函数参数为空 C 中有各种函数不接受任何参数。不带参数的函数可以接受一个 void。例如 int rand(void); |
3 | 指针指向 void 类型为 void * 的指针代表对象的地址,而不是类型。例如,内存分配函数 void *malloc( size_t size ); 返回指向 void 的指针,可以转换为任何数据类型。 |
C语言的枚举类型
枚举类型的定义:
enum 枚举名 {枚举元素1,枚举元素2,……}枚举变量;
enum 枚举名 {枚举元素1,枚举元素2,……};
enum {枚举元素1,枚举元素2,……}枚举变量;
也可以使用关键字typedef为该枚举类型自定义一个新的类型名字
typedef enum{枚举元素1,枚举元素2,……}自定义枚举名;
注:枚举元素之间以逗号的方式隔开。
实例:定义一个枚举类型来表示球的射门方向,在switch语句中来判断是否进球成功。
#include<string.h>
#include<stdio.h>
int main(void)
{
typedef enum
{
LEFT = 0,
MID = 1,
RIGHT = 2
}GOAL_DIR; //定义枚举类型GOAL_DIR
GOAL_DIR goal_dir; //定义枚举变量goal_dir
while(1)
{
int defend_dir = rand() % 3; //生成一个0-2的随机数
printf("请选择你的射门方向0:左,1:中间,2:右边\n");
scanf("%u", &goal_dir);
switch (goal_dir)
{
case LEFT:
printf("你的射门方向是左边\n");
if (goal_dir == defend_dir)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
break;
case MID:
printf("你的射门方向是中间\n");
if (goal_dir == defend_dir)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
break;
case RIGHT:
printf("你的射门方向是右边\n");
if (goal_dir == defend_dir)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
break;
default:
break;
}
printf("%d\n", defend_dir);
}
return 0;
}