#include <stdio.h> // 计算平均值的函数 float average(int arr[], int n) { int sum = 0; for(int i=0; i<n; i++) { sum += arr[i]; } return (float)sum / n; } int main() { // 初始化两个班的成绩数组 int class1[] = {80, 75, 90, 85, 70, 65, 92, 88, 78, 83, 95, 87, 79, 84, 91, 77, 73, 82, 89, 94, 81, 76, 86, 72, 93, 68, 69, 71, 67, 74, 66, 96, 97, 98, 99, 100, 61, 62, 63, 64}; int class2[] = {85, 90, 88, 92, 94, 91, 93, 89, 87, 86, 78, 79, 80, 81, 82, 83, 84, 95, 96, 97, 98, 99, 100, 76, 77, 72, 73, 74, 75, 68, 69, 70, 71, 65, 66, 67, 61, 62, 63, 64}; float avg1 = average(class1, 42); float avg2 = average(class2, 43); printf("Class 1 average score is: %.2f\n", avg1); printf("Class 2 average score is: %.2f\n", avg2); return 0; }检查错误
时间: 2023-07-02 14:09:39 浏览: 156
字符串函数string.h应用举例.-综合文档
这段代码没有明显的错误,但是有一些可以改进的地方。
1. 函数average可以使用double类型来计算平均值,这样结果更加精确。
2. 数组长度可以使用sizeof运算符来自动计算,这样代码更加灵活。
改进后的代码如下:
```c
#include <stdio.h>
double average(int arr[], int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
return (double)sum / n;
}
int main() {
int class1[] = {80, 75, 90, 85, 70, 65, 92, 88, 78, 83, 95, 87, 79, 84, 91, 77, 73, 82, 89, 94, 81, 76, 86, 72, 93, 68, 69, 71, 67, 74, 66, 96, 97, 98, 99, 100, 61, 62, 63, 64};
int class2[] = {85, 90, 88, 92, 94, 91, 93, 89, 87, 86, 78, 79, 80, 81, 82, 83, 84, 95, 96, 97, 98, 99, 100, 76, 77, 72, 73, 74, 75, 68, 69, 70, 71, 65, 66, 67, 61, 62, 63, 64};
int n1 = sizeof(class1) / sizeof(int);
int n2 = sizeof(class2) / sizeof(int);
double avg1 = average(class1, n1);
double avg2 = average(class2, n2);
printf("Class 1 average score is: %.2f\n", avg1);
printf("Class 2 average score is: %.2f\n", avg2);
return 0;
}
```
阅读全文