[英]Avergaging elements in array
我正在嘗試在數組中添加元素。 這只是一個計算學生平均成績的簡單程序。 我知道這可能是一種基本的編碼方式,我希望更有效地做到這一點。 但是我的代碼沒有返回平均值。 我將不勝感激任何幫助。 我確實用 for 循環嘗試過,但得到了同樣的錯誤答案。
#include <stdio.h>
int main()
{
int grades[6];
int average;
int sum = 0;
printf("Please enter your five test scores:\n");
scanf("%d", &grades[0]);
scanf("%d", &grades[1]);
scanf("%d", &grades[2]);
scanf("%d", &grades[3]);
scanf("%d", &grades[4]);
scanf("%d", &grades[5]);
sum = sum + grades[6];
average = sum / 5;
printf("The average of the students test scores is %d:\n", average);
return 0;
}
您應該將所有等級相加,然后除以它們的數量(在您的情況下,它是 6 而不是 5,因為grades
數組有 6 個元素)。 這是一個代碼示例:
#include <stdio.h>
int main()
{
int grades[6];
int average;
int sum = 0;
printf("Please enter your six test scores:\n");
scanf("%d", &grades[0]);
scanf("%d", &grades[1]);
scanf("%d", &grades[2]);
scanf("%d", &grades[3]);
scanf("%d", &grades[4]);
scanf("%d", &grades[5]);
for (int i = 0; i < 6; i++)
sum = sum + grades[i];
average = sum / 6;
printf("The average of the students test scores is %d:\n", average);
return 0;
}
我正在嘗試在數組中添加元素。
這可能已經是關於標題(和代碼)的錯誤軌道,它是關於平均數組中的元素。
如何構建陣列取決於您; 我選擇最簡單的方法。 一個重要的決定是:數組的大小和值的數量是否相同? 這就是n_grades
所做的。 數組初始化中的四個零說明了差異。
平均值很可能應該是浮點數。
平均值的一個令人討厭的問題是潛伏的溢出。 在這種情況下不太可能,但有一個更健壯(和優雅)的算法。 (double)
cast 是不優雅的部分,但由於除法是在兩個integers之間,所以需要它。 這仍然是緊湊的核心:
for (i = 0; i < n_grades; i++)
aver += (double) grades[i] / n_grades;
對應數學公式:
i<n
A = Sum G_i/n
i=0
(“總和”是大西格瑪)
#include <stdio.h>
int main()
{
int grades[] = {10,10,9,10,11,11,0,0,0,0};
int n_grades = sizeof grades / sizeof*grades; // use all elements
//n_grades = 6; // use only first n elements
double aver = 0;
for (int i = 0; i < n_grades; i++)
aver += (double) grades[i] / n_grades;
printf("The average of the students test scores is %f (n= %d):\n",
aver, n_grades);
return 0;
}
現在它打印:
The average of the students test scores is 6.100000 (n= 10):
或者,未注釋,即限制為 6 個等級:
The average of the students test scores is 10.166667 (n= 6):
您假設grades[6]
包含grades
數組中所有值的總和,這當然是錯誤的。
你需要類似的東西:
for (int i = 0; i < 6; i++)
sum = sum + grades[i];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.