Write a program in C language Compile and run the program averager.c. It is supp
ID: 649541 • Letter: W
Question
Write a program in C language
Compile and run the program averager.c. It is supposed to repeatedly read a number, then reads that number of values and prints their average. When you run it, you should see input and output like this:
Determine what the program does if it encounters garbage in the input or end of file when it is trying to read an input value. There are two cases to worry about. What does it do if instead of the 5 above, you enter "garbage"? And what does it do if instead of the "10 20 ... 50", you enter "10 20 garbage"? Fix the program so that if it receives garbage input instead of integers for the expected number of values, it prints the following error message and quits.
Fix the program so that it prints the following error message and quits if it receives garbage input instead of integers when it is trying to read one of the values it should be averaging.
/* File : averager.c *
*/
/*
* Read in a number of values to read and then print the average
* of those values.
*/
#include <stdio.h>
int main()
{
int expected;
int count;
double sum;
int value;
while (scanf("%d", &expected) != EOF)
{
sum = 0;
for (count = 0; count < expected; count++)
{
scanf("%d", &value);
sum += value;
}
printf("Average of %d values is %.2f ",
count, count != 0 ? sum / count : 0.0);
}
}
Explanation / Answer
#include <stdio.h>
int main()
{
int number;
int count;
double sum;
int value;
bool flag=true;
while(scanf("%d", &number)!=0)
{
sum = 0;
for (count = 0; count < number; count++)
{
int n=scanf("%d", &value);
if(n==0)
{
printf("Error! Can't read expected value #%d. ",count);
flag=false;
break;
}
sum += value;
}
printf(" Average of %d values is %.2f ",
count, count != 0 ? sum / count : 0.0);
}
if(flag)
printf("Error! Can't read number of expected values. ");
system("pause");
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.