[英]This is a c code to find the average in an array of 50 elements using a function
[英]Find the average of 50 random numbers in an array- C Programming
我已經弄清楚了如何在一個數組中顯示50個隨機數。 數字介於1到500之間。我在當前代碼中找不到平均值很麻煩,因為它只會顯示為零。 有人能幫我嗎?
int num[SIZE] = {0};
int count = 0;
int i;
int total = 0;
int value;
float avg = 0;
srand((unsigned)time(NULL)); //SEEDS RAND FUNCTION
printf("Display the numbers in the range of [1, 500]. \n"); //displays random numbers
for(i = 0; i < 50; i++)
{
value = rand()%500 + 1;
printf("%i\n", value);
total = total + num[i];
avg = (float)total/50;
}
//Display Output
printf("The average of all the numbers is %i \n", avg);
1) avg = (float)total/50;
應該不在您的for
循環中。
2) total = total + num[i];
應該是total = total + value;
3)您的printf
聲明應為:
printf("The average of all the numbers is %f \n", avg);
4)另外,您不使用num[]
數組。
total = total + num[i];
在這里num[i]
和整個數組包含0。因此total
將保持為0。因此,您需要
num[i]=value;
在計算total
之前。 另外,平均值應在循環后計算。 不要忘記在最后一個printf
使用%f
代替%i
,因為avg
是float
。
由於沒有將value
分配給數組元素num[i]
因此得到0。 在循環中,您還應該
num[i] = value;
total = total + num[i];
並且您需要將avg
計算移出for循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.