- 1

Hello can anyone please tell me the problem of this code

It runs well but gives a wrong output https://code.sololearn.com/c0ZPD6GjH8de/?ref=app

29th Jan 2022, 7:28 PM
Sir Victor Wilfred
Sir Victor Wilfred - avatar
5 Answers
+ 1
Line 19: You are comparing an int to a char, obviously you are not going to get the expected result. Line 41: %d should be %f, since average is a float. Line 33: use "average = (float) total/counter" You should use a do..while loop
29th Jan 2022, 7:36 PM
CGM
CGM - avatar
+ 1
Sir Victor, Like Cristian was stating you have a very common integer math error. Integers in C negate the decimals. integer math: 1 /2 == 0 9/10 == 0 float math: 1/2 == .5 9/10 == .9 Also you are trying to break your loop by typing q with a format specifier of %d. That will create problems. Another method would be to take the grades in as a string then convert them. I made some adjustments: https://code.sololearn.com/ciHPZeF1XtTF
29th Jan 2022, 8:22 PM
William Owens
William Owens - avatar
+ 1
Here is a solution using getchar() #include<stdio.h> int main() { int total, counter, grade; total = 0; counter = 0; float average; char ch; while(ch != 'q' ) { printf("\nEnter the grade ( type \'q\' to quit ) : "); scanf("%d", &grade); ch = getchar(); if (ch != 'q') { total = total + grade; counter++; printf("total : %d\n", total); printf("counter value : %d\n", counter); } } if (counter != 0) { average = (float)total / counter; } else { printf("No grades were entered !! "); } printf("The computed Average is %.2f", average); return 0; }
29th Jan 2022, 10:05 PM
Jan
Jan - avatar
+ 1
Wow thanks everyone, I'm a beginner, I'm still learning. šŸ˜‰
31st Jan 2022, 1:25 PM
Sir Victor Wilfred
Sir Victor Wilfred - avatar
0
@Quantum: That was very cleaver using the getchar() after the scanf(). Nicely done.
30th Jan 2022, 1:28 AM
William Owens
William Owens - avatar