12.1 单一的结构
生日
#include <stdio.h>
struct Date//⭐️⭐️语法
{
int month;
int day;
int year;
};
int main()
{
struct Date birth;//⭐️⭐️
birth.month = 12;//⭐️⭐️
birth.day = 28;//⭐️⭐️
birth.year = 1987;//⭐️⭐️
printf("My birth date is %d/%d/%d\n",
birth.month,birth.day,birth.year % 100);
return 0;
}
12.2 结构的数组
数据量更大,且遵循规律。比如,员工编号,员工姓名,工资
#include <stdio.h>
#define NUMRECS 5
struct PayRecord /* construct a global structure type */
{
int id;
char name[20];
double rate;
};
int main()
{
int i;
struct PayRecord employee[NUMRECS] = {{32479, "Abrams, B.", 6.72},
{33623, "Bohm, P.", 7.54},
{34145, "Donaldson, S.", 5.56},
{35987, "Ernst, T.", 5.43},
{36203, "Gwodz, K.", 8.72}
};
for (i = 0; i < NUMRECS; i++)
printf("%d %-20s %4.2f\n",
employee[i].id,employee[i].name,employee[i].rate);
return 0;
}
12.3 传递结构和返回结构
传递
#include <stdio.h>
struct Employee /* declare a global structure type */
{
int idNum;
double payRate;
double hours;
};
double calcNet(struct Employee); /* function prototype */
int main()
{
struct Employee emp = {6787, 8.93, 40.5};
double netPay;
netPay = calcNet(emp); /* pass copies of the values in emp */
printf("The net pay of employee %d is $%6.2f\n",
emp.idNum,netPay);
return 0;
}
double calcNet(struct Employee temp)
/* temp is of data type struct Employee */
{
return(temp.payRate * temp.hours);
}
(*pt).idNum 能用 pt->idNum 代替
#include <stdio.h>
struct Employee /* declare a global structure type */
{
int idNum;
double payRate;
double hours;
};
double calcNet(struct Employee *); /* function prototype */
int main()
{
struct Employee emp = {6787, 8.93, 40.5};
double netPay;
netPay = calcNet(&emp); /* pass an address*/
printf("The net pay for employee %d is $%6.2f\n",
emp.idNum, netPay);
return 0;
}
double calcNet(struct Employee *pt) /* pt is a pointer to a */
{
/* structure of Employee type */
return(pt->payRate * pt->hours);
}
返回一个完整的结构给main()
#include <stdio.h>
struct Employee /* declare a global structure type */
{
int idNum;
double payRate;
double hours;
};
struct Employee getValues(); /* function prototype */
int main()
{
struct Employee emp;
emp = getValues();
printf("The employee id number is %d\n", emp.idNum);
printf("The employee pay rate is $%5.2f\n", emp.payRate);
printf("The employee hours are %5.2f\n", emp.hours);
return 0;
}
struct Employee getValues()
{
struct Employee newemp;
newemp.idNum = 6789;
newemp.payRate = 16.25;
newemp.hours = 38.0;
return (newemp);
}
12.4 联合union(略)
union是一种保留两个或多个变量在内存中相同区域的数据类型,这些变量可以是不同的数据类型。
union
{
char key;
int num;
double price;
}
网友评论