问题:
从键盘输入学生的信息,并统计学生的成绩
实现
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
//-----------------------------------------------------
/** 结构体的嵌套 */
//-----------------------------------------------------
struct address {
char city[64]; // 城市
char street[64]; // 街道
int number; // 门牌号
};
typedef struct address Address; // 使用的typedef对类型进行定义
// typedef 是用来定义类型的关键字, 类似的还有下面的使用
typedef unsigned char Byte; // 一个无符号字符类型的长度为一个字节
/** typedef 可以和结构体的定义一起写。*/
typedef struct name {
char familyName[32];
char firstName[32];
}Name;
/** 使用typedef的时候,可以使用的匿名结构体*/
typedef struct scores{ ///注意这个地方struct关键字之后没有名字
int math;
int english;
}Scores;
struct student {
Scores scrs; /// typedef定义后的可以不用写struct关键字
struct address addr;
Name name;
int age;
};
int calculateTotalScore(struct student * stdnt) // 使用结构体指针作为参数
{
int totalScore = 0;
totalScore += stdnt->scrs.math; /// 因为stdnt是指针所有要使用“->”
totalScore += stdnt->scrs.english;
return totalScore;
}
测试:
int testStudent()
{
struct student stdnt;
strcpy(stdnt.name.firstName, "jack"); /// 数组不能直接赋值,需要拷贝
strcpy(stdnt.name.familyName, "ma");
stdnt.scrs.math = 99;
stdnt.scrs.english = 30;
strcpy(stdnt.addr.city, "wuhan");
strcpy(stdnt.addr.street, "guanshan");
stdnt.addr.number = 100;
stdnt.age = 20;
int totalScore = calculateTotalScore(&stdnt);
printf("totalScore of student %s, is:%d", stdnt.name.familyName,
totalScore);
return 0;
}