我是C语言编码的新手,我正在尝试获得数组的平均值,但由于某种原因它没有计算,它给了我0.0的结果。
我该如何解决这个问题。感谢
#include <stdio.h>
float grades_average(float grades[7]);
int main() {
float grades[7]={98.8, 97.9, 99.3, 99.8, 99.6, 99.4, 99.9};
float average;
average = grades_average(grades);
printf("Average is: %.2f",average);
return 1;
}
float grades_average(float grades[7]){
int i;
float sum = 0;
float average = 0.0;
/* calculate the sum of grades using for loop*/
for(i = 0; i <= 7; i++){
sum = sum + grades[7];
}
average = sum/7;
return average;
}
输出结果为:
Average is: 0.00
答案 0 :(得分:3)
最小变更解决方案:
float grades_average(float grades[7]){
int i;
float sum = 0;
float average = 0.0;
/* calculate the sum of grades using for loop*/
for(i = 0; i < 7; i++){
sum = sum + grades[i];
}
average = sum/7.f;
return average;
}
for(i = 0; i <= 7; i++){
更改为for(i = 0; i < 7; i++){
。成绩的有效指标仅为0-6。 7超出界限。sum = sum + grades[7];
更改为sum = sum + grades[i];
您需要一遍又一遍地检查每个元素,而不是(超出)最后一个元素。average = sum/7;
更改为average = sum/7.f;
.f
确保无整数除法。这在分裂期间保留了小数。我希望有所帮助!
答案 1 :(得分:2)
这是完整的代码。有2个变化,第20行和第23行
#include <stdio.h>
float grades_average(float grades[7]);
int main() {
float grades[7]={98.8, 97.9, 99.3, 99.8, 99.6, 99.4, 99.9};
float average;
average = grades_average(grades);
printf("Average is: %.2f",average);
return 1;
}
float grades_average(float grades[7]){
int i;
float sum = 0;
float average = 0.0;
/* calculate the sum of grades using for loop*/
/*Changed here to <7 because i takes 0,1,2,3,4,5,6 which are 7 elements, your code is <=7 which takes 0.......7 which are 8 elements */
for(i = 0; i < 7; i++){
/*Changed here to i from 7, your code everytime sums out of bound element, Garbage value since grades[7] does not exist*/
sum = sum + grades[i];
}
average = sum/7;
return average;
}
答案 2 :(得分:2)
for(i = 0; i <= 7; i++){}
更改为for(i = 0; i < 7; i++){}
,因为
完全你有7个元素,从0
到6
。将sum = sum + grades[7];
更改为sum = sum + grades[i];
,因为成绩[7]只会包含数组的最后一个值,但您想要添加数组中的所有值。
float grades_average(float grades[7]);
int main() {
float grades[7]={98.8, 97.9, 99.3, 99.8, 99.6, 99.4, 99.9};
float average;
average = grades_average(grades);
printf("Average is: %.2f",average);
return 1;
}
float grades_average(float grades[7]){
int i;
float sum = 0;
float average = 0.0;
/* calculate the sum of grades using for loop*/
for(i = 0; i < 7; i++){
sum = sum + grades[i];
}
average = sum/7.f;
return average;
}
希望有所帮助..
答案 3 :(得分:0)
尝试将i代替7,
sum = sum + grades[7];
像
sum = sum + grades[i];
和你的循环从0到6
答案 4 :(得分:0)
代替使用此
sum = sum + grades[7];
使用
sum = sum + grades[i];
然后它会起作用。