c 语言结构体
#include <stdio.h>
struct student{
char *name;
int num;
int age;
char group;
float score;
};
int main() {
struct {
char *name;
int num;
int age;
char group;
float score;
} stu1;
stu1.name = "eric";
stu1.num = 1234;
stu1.age = 19;
stu1.group = 'A';
stu1.score = 99.9;
printf("stu1.name =%s stu1.num = %d stu1.age = %d stu1.group = %c stu1.score = %.1f \n", stu1.name, stu1.num, stu1.age, stu1.group, stu1.score);
return 0;
}
在实际编程中,有些数据的取值往往是有限的,只能是非常少量的整数,并且最好为每个值都取一个名字,以方便在后续代码中使用,比如一个星期只有七天,一年只有十二个月,一个班每周有六门课程等。
#include <stdio.h>
#define Mon 1
#define Tues 2
#define Wed 3
#define Thurs 4
#define Fri 5
#define Sat 6
#define Sun 7
#define PI 3.14
int main() {
int day;
scanf("%d", &day);
switch (day) {
case Mon:
puts("Monday"); break;
case Tues:
puts("Tuesday"); break;
case Wed:
puts("Wednesday"); break;
case Thurs:
puts("Thursday"); break;
case Fri:
puts("Friday"); break;
case Sat:
puts("Saturday"); break;
case Sun:
puts("Sunday"); break;
default:
puts("Error !");
}
return 0;
}
```![在这里插入图片描述](https:
#define命令虽然能解决问题,但也带来了不小的副作用,导致宏名过多,代码松散,看起来总有点不舒服。C语言提供了一种枚举(Enum)类型,能够列出所有可能的取值,并给它们取一个名字。
枚举类型的定义形式为:
```c
enum typeName{ valueName1, valueName2, valueName3, ...... };
#include <stdio.h>
#define PI 3.14
int main() {
enum week{Mon=1, Tues=3, Wed, Thurs, Fri, Sat, Sun};
printf("Wed = %d", Wed);
return 0;
}
ennum版本
#include <stdio.h>
int main() {
enum week{Mon=1, Tues=3, Wed, Thurs, Fri, Sat, Sun} day;
scanf("%d", &day);
switch (day) {
case Mon:
puts("Monday"); break;
case Tues:
puts("Tuesday"); break;
case Wed:
puts("Wednesday"); break;
case Thurs:
puts("Thursday"); break;
case Fri:
puts("Friday"); break;
case Sat:
puts("Saturday"); break;
case Sun:
puts("Sunday"); break;
default:
puts("Error !");
}
return 0;
}
|