I am creating a program that calculates the average for a bunch of numbers. The first input is the number of values, and the second output is/are the numbers. For example, with the inputs of the following, I would get the outputs afterward.
5
10 20 30 40 50
Average of 5 values is 30.00
7
15 20 40 50 60 40 50
Average of 7 values is 39.29
I want to make the program more robust so that it will only read integer values. If I were to enter the following, this would be the ouput that I want.
garbage
10 20 whatever 40 50
Error! Can't read number of expected values.
or
5
10 20 30 40 50
Average of 5 values is 30.00
6
50 70 whatever 40 60
Error! Can't read expected value #2.
Average of 2 values is 60.00
Here's my program so far:
/* Read in a number of values to read and then print the average
* of those values.
*/
#include <stdio.h>
int main()
{
/* Declare variables */
int expected;
int count;
double sum;
int value;
/* While the input (number of values) is not equal to end of file */
while (scanf("%d", &expected) != EOF)
{
/* Initializee sum at 0 */
sum = 0;
/* Initialize count at 0 */
/* While the count is less than the expected count (input),
increase count by one */
for (count = 0; count < expected; count++)
{
/* Read input of values for the average */
scanf("%d", &value);
/* Sum is equal to previous sum increased by value */
sum += value;
}
/* Print average of all values */
printf("Average of %d values is %.2f\n",
count, count != 0 ? sum / count : 0.0);
if (expected < 0 || expected == getchar())
{
printf("Error! Can't read number of expected values.");
}
}
}
I want to print an error if a character or number less than 0 is entered (for the expected value of inputs). My program compiles, but this is just not working out. Any suggestions please?