C程序设计 (谭浩强) 第四版 例8.14
例 8.14 有一个班,3个学生,各学4门课,计算总平均分数以及第n个学生的成绩。
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块
#include <stdio.h>
#include <stdlib.h>
#define M 3
#define N 4
void initialStu(float ***stu, int m, int n){
*stu = (float**)malloc(m * sizeof(float*));
for(int i = 0; i < m; i++){
(*stu)[i] = (float*)malloc(n * sizeof(float));
}
}
void inputStu(float **stu, int m, int n){
printf("Enter the scores of %d student in %d courses:\n", m, n);
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
printf("Enter the score of No.%d student in No.%d course: ", i + 1, j + 1);
scanf("%f", *(stu + i) + j);
while(*(*(stu + i) + j) < 0 || *(*(stu + i) + j) > 100){
printf("Score Error! Retry!\nEnter the score of No.%d student in No.%d course: ", i + 1, j + 1);
scanf("%f", *(stu + i) + j);
}
}
}
}
void averageStu(float **stu, int m, int n){
float sum = 0.0;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
sum += *(*(stu + i) + j);
}
}
printf("\nThe average score is %.2f\n\n", sum / (m * n));
}
void search(float **stu, int m , int n, int nStu){
float **p;
for(p = stu; p < stu + m; p++){
if(p == stu + (nStu - 1)){
printf("No.%d student scores: ", nStu);
for(int j = 0; j < n; j++){
printf("%5.2f ", *(*p + j));
}
printf("\n");
break;
}
}
}
void freeStu(float ***stu, int m){
for(int i = 0; i < m; i++){
free((*stu)[i]);
}
free(*stu);
}
int main(){
float **stu = NULL;
int nStu;
initialStu(&stu, M, N);
inputStu(stu, M, N);
averageStu(stu, M, N);
printf("Enter the student you want to find: ");
scanf("%d", &nStu);
search(stu, M, N, nStu);
freeStu(&stu, M);
system("pause");
return 0;
}