簡體   English   中英

在數組中找到50個隨機數的平均值

[英]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 ,因為avgfloat

由於沒有將value分配給數組元素num[i]因此得到0。 在循環中,您還應該

num[i] = value;
total = total + num[i];

並且您需要將avg計算移出for循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM