Minmax数字数组

时间:2013-09-07 03:06:03

标签: c arrays max min minmax

此程序仅从用户获得5个数字 将它们存储在一个数组中。获取输入数字的最小值,最大值和平均值。这是我制作的代码:

#include <stdio.h>
#include <conio.h>

int main()
{
int num[5];
int min, max=0;
int counter;
float average, total;

max = num[0];
min = num[2];

for(counter=0; counter<=4; counter++)
{
    printf("Enter a number: ");
    scanf("%d", &num[counter]);

    if(num[counter]>max)
    {
        max = num[counter];
    }

    if (num[counter]<min)
    {
        min = num[counter];
    }
}

total = max+min;
average = total/2;

printf("The maximum number is: %d\n", max);
printf("The minimum number is: %d\n", min); 
printf("The average is: %d", average);


getch();
return 0;
}

FInally用最小值和最大值修正了我的错误,现在我遇到了平均值的问题。我应该只获得最小和最大数字的平均值,但它仍然显示平均值为零。有人可以帮忙吗? Thankkyouuu。

4 个答案:

答案 0 :(得分:1)

  1. 您的平均值计算错误;你需要使用total/num(记得使用浮动):

    total += num[counter];
    
  2. maxmin未正确初始化:num[0]num[2]在您初始化时可能是任何内容。

答案 1 :(得分:1)

//get memory address and store value in it.
void getValue(int *ptr)
{
    printf("Enter a number: ");
    scanf("%d", ptr);
}
int main()
{
    //initialized n=5 as per your requirement. You can even get the value at run time.
    int min, max, counter,n=5;
    int num[n];
    float average,total;
    getValue(num); //get num[0]
    min=max=total=num[0]; //Initialize min,max,total with num[0]
    for(counter=1; counter<n; counter++)
    {
        getValue(num+counter); //get num[counter]
        num[counter]>max?max = num[counter]:max; //find max
        num[counter]<min?min = num[counter]:min; //find min
        total+=num[counter]; // total = total + num[counter]
    }
    average = total/n; 
    printf("The maximum number is: %d\n", max);
    printf("The minimum number is: %d\n", min); 
    printf("The total is: %f\n", total); 
    printf("The average is: %f\n", average);
return 0;
}

答案 2 :(得分:0)

除了计算average错误(不仅仅是total/2)之外,还需要在printf中使用正确的格式说明符:

printf("The average is: %g", average);

您正在使用%d告诉printf期望一个整数,但是您给它一个float

答案 3 :(得分:0)

应该初始化1分钟和最大值

int min = INT_MAX;
int max = INT_MIN;

2你需要保持你的总数

int total = 0;
...
// inside loop
scanf("%d", &num[counter]);
total += num[counter];

3最后打印平均值,建议转到浮点。

printf("The average is: %.1f", (double)total/counter);