The code is OK, only the missing value is fflush(stdin) ; to scanf function. It can always be used before the scanf function to avoid these errors. The act of pressing the 'Enter' key gives a new line character \\ n \ as an input to the stdin buffer. Therefore, the first scanf function in a loop takes it as an input and does not wait for the user to enter values.
#include <stdio.h> #include <ctype.h> // For tolower() function // int main(void) { char answer = 'N'; double total = 0.0; // Total of values entered // double value = 0.0; // Value entered // int count = 0; printf("This program calculates the average of" " any number of values."); while(1) { printf("\nEnter a value: "); fflush(stdin); scanf("%lf", &value); total+=value; ++count; printf("Do you want to enter another value? (Y or N): "); fflush(stdin); scanf("%c", &answer); if(tolower(answer) == 'n') break; } printf("The average is %.2lf.", total/count); getch(); return 0; }
Also add the getch() function to view the results if you use the console.
source share