0

该程序仅从用户那里获取 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;
}

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

4

4 回答 4

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;
}
于 2013-09-07T04:08:32.730 回答
1
  1. 你计算的平均值是错误的;你需要使用total/num(记住使用浮动):

    total += num[counter];
    
  2. max并且min被错误地初始化: num[0],num[2]在你初始化它们时可能是任何东西。

于 2013-09-07T03:19:37.270 回答
0

Aside from your calculation of average being wrong (it's not just total/2), you need to use the correct format specifier in the printf:

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

You are using %d which tells printf to expect an integer, but you're giving it a float.

于 2013-09-07T03:07:26.947 回答
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);
于 2013-09-07T04:16:10.143 回答