I want to calculate average of the numbers entered by the user, where the user can enter as many numbers as he/she wants , i.e., the loop will stop only when the user wants.
To stop the loop from user's input, I tried this:
while (true)
{
/* code here */
printf("\nContinue? (Y/N)");
char res;
scanf("%c", &res);
if (res == 'N') {
break;
}
}
I expect output like this:
Enter number: 32
Continue? (Y/N) Y
Enter number: 78
Continue? (Y/N) N
55.0000
But I am getting this output:
Enter number: 32
Continue? (Y/N)
Enter number: 78
Continue? (Y/N)
Enter number: N
Continue? (Y/N)
62.666668
Here is my full code:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int sum = 0;
int count = 0;
while (true) {
printf("\nEnter number: ");
int a;
scanf("%d", &a);
sum += a;
count += 1;
printf("\nContinue? (Y/N)");
char res;
scanf("%c", &res);
if (res == 'N') {
break;
}
}
float avg = (sum*1.0)/count;
printf("\n%f", avg);
return 0;
}
I tried a lot to fix the issue myself, but with no luck. I am still unsure of where exactly is my fault. Please help me to fix this.
"Y"?