【问题标题】:Minmax numbers array最小最大数字数组
【发布时间】:2013-09-07 03:06:02
【问题描述】:

这个程序只从用户那里得到 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;
}

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

【问题讨论】:

  • 学习使用惯用的for (counter = 0; counter &lt; 5; counter++)循环而不是在条件中使用counter &lt;= 4
  • 另外,您可能会注意到您根本不需要数组。您可以简单地将不定数量的值读取到单个变量中,一次一个,然后使用该变量执行最小、最大和求和操作。那么您将不限于固定大小的数组。当然,您必须正确处理来自 scanf() 的错误和 EOF,但无论如何您都应该这样做。
  • 完成后不要再破坏你的问题了。这是你今天第三次这样做了。

标签: c arrays max min minmax


【解决方案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;
}

【讨论】:

  • @chux 提供失败的测试用例。最小值和最大值总是用数组的第一个元素初始化。 SO min 和 max 不能为零,除非输入值为零。
【解决方案2】:
  1. 你计算的平均值是错误的;你需要使用total/num(记得使用float):

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

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

      【解决方案4】:

      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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多