生成数组中的随机数并计算平均值,最大值,最小值,总和

时间:2017-04-12 01:16:08

标签: c arrays random numbers generator

此代码应生成30个随机数,0-100,并打印平均值,最大值和最小值。但它有逻辑错误,我不能帮助,但认为我犯了一个愚蠢的错误。

****代码应该从0-100生成30个数字,并显示mean,max和min ****

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define SIZE 30

int generateRandom(void); 

int main(void)
{

    int points[SIZE], i, sum, max, min, num; 
    double average; 

    srand(time(NULL));                      /*Seed random number generator*/

    num = generateRandom();                 /*Genrate the random numbers*/

    printf("num = %d\n", num);              /*Print the random numbers*/

    sum = 0; 
    for ( i = 0; i < SIZE; i++)             /*Find the average*/
    {
        sum += points[i]; 
        average = sum / SIZE; 
    }
    printf("Average = %f", average);        /*Print the average*/


    max = points[0];                        /*initialize the max to 0*/
    for ( i = 0; i < SIZE; i++)             /*find the min*/
    {
        if (points[i] > max)
        {
            max = points[i]; 
        }
    }
    printf("Maximum = %d\n", max);          /*print the maximum number*/

    min = points[0];                        /*initialize the min*/
    for ( i = 0; i < SIZE; i++)             /*Find the min*/
    {
        if (points[i] < min)
        {
            min = points[i]; 
        }
    }
    printf("Minimum = %d\n", min);          /*Print the minimum number*/


    return 0; 

}

int generateRandom(void)
{
    int random; 

    random = rand() % 101; 

    return random;
}

2 个答案:

答案 0 :(得分:0)

您只会生成一个随机数,存储在num中。然后,您的代码就像在points中存储了30个随机数一样。但它永远不会发生这种情况。

答案 1 :(得分:0)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define SIZE 30

int generateRandom(void);

int main(void)
{

    int points[SIZE],i,sum,max,min,num;
    double average;

    srand(time(NULL));                             

    for(i = 0; i < SIZE; i++){
        points[i] = generateRandom();
    }

    sum = 0;
    for(i = 0; i < SIZE; i++)
    {
        sum += points[i];
    }
    average = (sum * 1.0) / SIZE;   /*you need double here*/
    printf("Average = %f\n",average);      


    max = points[0];                       
    for(i = 1; i < SIZE; i++)            
    {
        if(points[i] > max)
        {
            max = points[i];
        }
    }
    printf("Maximum = %d\n",max);     

    min = points[0];                     
    for(i = 1; i < SIZE; i++)            
    {
        if(points[i] < min)
        {
            min = points[i];
        }
    }
    printf("Minimum = %d\n",min); 

    return 0;
}

int generateRandom(void)
{
    int random;

    random = rand() % 101;

    return random;
}