Getting the min, max, and ave of the five numbers inputted

眉间皱痕 提交于 2019-12-08 08:32:08

问题


I'm trying to work on a program in C that gets 5 input numbers and then store these in an array. After getting the the 5 numbers, I must be getting the min, max and the average of the MINIMUN AND MAXIMUM numbers inputted and not all of the five. So here's the code that I made. When I get the maximum number, it seems to be working fine. But when it come's to the min, it's still same as the maximum and so I'll be getting a different average.

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

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

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

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

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

total = min + max;
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;
}

回答1:


Since this is a learning exercise, I wouldn't correct your code, but point out what needs to be fixed:

  • Arrays in C are indexed from zero, not from one, so the counter should go from 0 to 4, inclusive
  • min is an int, while num is an array, so the assignment min=num is invalid
  • scanf should put the data into &num[count], not &num[5]
  • In the way that you coded your loop you do not need an array at all: you need the last number entered.
  • total cannot be computed as min+max; you need to keep a running total, updating it on each iteration.


来源:https://stackoverflow.com/questions/18668824/getting-the-min-max-and-ave-of-the-five-numbers-inputted

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!