成绩,求平均成绩。"/>
C //例 7.10 有一个一维数组score,内放10个学生成绩,求平均成绩。
C程序设计 (第四版) 谭浩强 例 7.10
例 7.10 有一个一维数组score,内放10个学生成绩,求平均成绩。
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块
方法:使用指针、动态分配内存
#include <stdio.h>
#include <stdlib.h>#define N 10void initialScore(float **score, int n){*score = (float*)malloc(n * sizeof(float));
}void inputScore(float *score, int n){printf("Enter the scores of %d students: ", n);for(int i = 0; i < n; i++){scanf("%f", &score[i]);}
}float average(float *score, int n){float sum = 0.0;for(int i = 0; i < n; i++){sum += score[i];}return sum / n;
}void freeScore(float **score){free(*score);
}int main(){float *score = NULL;initialScore(&score, N);inputScore(score, N);printf("Average = %.2f\n", average(score, N));freeScore(&score);system("pause");return 0;
}
更多推荐
C //例 7.10 有一个一维数组score,内放10个学生成绩,求平均成绩。
发布评论