- 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
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
+ 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
+ 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;
}
+ 1
Wow thanks everyone, I'm a beginner, I'm still learning. š
0
@Quantum:
That was very cleaver using the getchar() after the scanf(). Nicely done.