Reputation: 45
I try to code with the given code from C programming language textbook, Joy of C, I typed exactly according to the book. This code seem perfect to me and it works fine, except at avg_score which won't compute and display correctly.
It's always displayed 0, so I think the problem might be caused by
total_score = total_score + next_score;
doesn't work properly.
I would like to thank in advance for anybody who give me a hand, especially who know what the cause is.
edit1. I sorry very much for my mistake. I intend to ask for avg_score, not total score. I did check the cause and it appear to be total_score is alway 0.
edit2. my expecting result is something like the following (may not exact)
Example Input:
Score? 91
91 - PASS
Score? 70
70 - PASS
Score? 69
69 - FAIL
Score? h
3 score entered, 2 pass
average score is 76.67
Source Code:
#include<stdio.h>
#include<stdlib.h>
#define PASSING_SCORE 70
int main()
{
int next_score;
int n;
int score_count;
int pass_count;
int fail_count;
int avg_score;
int total_score;
score_count = 0;
pass_count = 0;
fail_count = 0;
total_score = 0;
printf("Score?");
n = scanf("%i",&next_score);
while(n==1)
{
score_count = score_count + 1;
total_score = total_score + next_score;
if (next_score >= PASSING_SCORE)
{
printf("%i - PASS\n",next_score);
pass_count = pass_count + 1;
}
else
{
printf("%i - FAIL\n",next_score);
fail_count = fail_count + 1;
}
printf("Score?");
n = scanf("%i",&next_score);
}
if (score_count == 0)
avg_score = 0;
else
avg_score = total_score/score_count;
printf("\n%i score entered, %i pass, %ifail.\n",
score_count,pass_count,fail_count);
printf("average score is %.2f\n",avg_score);
return EXIT_SUCCESS;
}
Upvotes: 2
Views: 119
Reputation: 81986
By changing two lines of code, I believe I have the correct output:
Declare avg_score
as a double.
double avg_score;
Cast total_score
to a double when calculating avg_score
so that we don't use integer division:
if (score_count == 0)
avg_score = 0;
else
avg_score = (double) total_score/score_count;
Let's try running it with these fixes:
[8:59pm][wlynch@watermelon /tmp] ./foo
Score?91
91 - PASS
Score?70
70 - PASS
Score?69
69 - FAIL
Score?h
3 score entered, 2 pass, 1fail.
average score is 76.67
Upvotes: 1
Reputation: 23813
Look at your compiler warnings : avg_score
is declared as an integer, but you print with %.2f
.
You probably meant to declare it as a floating point number : double
would work. Or print it as an integer with %d
, I'm not sure what your code example is about.
EDIT:
To correctly compute your average (as commented by @Mike), you should cast one of the quotient operands to double
:
avg_score = total_score/(double)score_count;
If not, you would get the integer quotient.
Upvotes: 5