习题 9.3 编写一个函数print,打印一个学生的成绩数组,该数组中有5个学生的数据记录,每个记录包括num,name,score[3],用主函数输入这些记录,用print函数输出这些记录。
C程序设计(第四版) 谭浩强 习题9.3 个人设计
习题 9.3 编写一个函数print,打印一个学生的成绩数组,该数组中有5个学生的数据记录,每个记录包括num,name,score[3],用主函数输入这些记录,用print函数输出这些记录。
代码块:
方法1:
#include <stdio.h>
struct student
{
int num;
char name[10];
float score[3];
} stu[5];
void print(struct student s[]);
int main()
{
int i, j;
for (i=0; i<5; i++){
printf("Please enter No.%d student num, name, score: ", i+1);
scanf("%d %s", &stu[i].num, stu[i].name);
for (j=0; j<3; scanf("%f", &stu[i].score[j++]));
}
print(stu);
return 0;
}
void print(struct student s[])
{
int i, j;
for (i=0; i<5; printf("\n"), i++){
printf("%d %-10s ", s[i].num, s[i].name);
for (j=0; j<3; printf("%.2f ", s[i].score[j++]));
}
}
方法2:
#include <stdio.h>
#include <stdlib.h>
struct Student{
int num;
char name[20];
float score[3];
};
void input(Student *st);
void print(Student *st);
int main()
{
Student *stu=(Student*)malloc(5*sizeof(Student));
input(stu);
print(stu);
system("pause");
return 0;
}
void input(Student *st)
{
int i, j;
Student *p;
for (p=st, i=0; p<st+5; p++, i++){
printf("Please enter No.%d student info: ", i+1);
scanf("%d %s", &p->num, p->name);
for (j=0; j<3; scanf("%f", &p->score[j++]));
}
}
void print(Student *st)
{
int i;
Student *p;
for (p=st, printf("Result:\n"); p<st+5; p++){
printf("%d %7s ", p->num, p->name);
for (i=0; i<3; printf("%.2f ", p->score[i++]));
printf("\n");
}
}
还没有评论,来说两句吧...