xin xin - 1 year ago 101
C Question

C program: Simple math program

Want to print for example
Grade: 4/5
80 percent

Program ask a user how many math problems they want to solve and prints out the number of "wrongs/the number of rights" and their grade. I think I dont have my math right at the end of the code cause its printing out for example:
Grade: 4/5
-7446528 percent


# include <stdio.h>

int main()
int NumberOfTimes, AddAns, SubAns, AddCorrect=0, SubCorrect=0, CorrectAnsAdd, CorrectAnsSub, TotalCorrect, TotalWrong, Add;
int i,a,b,c,d,e,f,g;
float percent;

printf("-------------------MATH QUIZ------------------------\n");
printf("Enter the number of Math problems you want to solve:"); //enters the # of problems the program produces
scanf("%d", &NumberOfTimes);
//Random number generator
for (i=0;i<NumberOfTimes;++i)
b = rand() %3 + 1;
c = rand() %3 + 1;
a = rand() %2 + 1;

//Random addition problems
if (a == 1)
printf("%d + %d = ", b,c);
scanf("%d", &AddAns);
d = b + c;
if (AddAns == d)
printf(" +Correct\n");
AddCorrect = AddCorrect + 1;
//Random subtraction problems
printf(" +Wrong, it was %d\n", d);
AddIncorrect = AddIncorrect + 1;
if (a == 2)
printf("%d - %d = ", b,c);
scanf("%d", &SubAns);
g = b - c;
//Produces right or wrong answers
if (SubAns == g)
printf(" +Correct\n");
SubCorrect = SubCorrect + 1;
printf(" +Wrong, it was %d\n", g);
SubIncorrect = SubIncorrect + 1;
//Producing the output to wrong/right numbers and grade percentage
TotalCorrect = AddCorrect + SubCorrect;
printf("Grade: %d/%d\n",TotalCorrect,NumberOfTimes);
printf("%d percent \n", percent);
return 0;

qxz qxz
Answer Source

There are a few things going on. First, to print a float with printf, use %f. %d is for ints.

Secondly, when you calculate percent, you're accidentally using integer division. Since NumberOfTimes and TotalCorrect are both integers, NumberOfTimes/TotalCorrect performs integer division and produces an int. It's only converted to a float after the whole initializing expression is evaluated. Use this instead:

percent = (float)TotalCorrect / NumberOfTimes;
// OR, if you want an actual percent:
percent = 100.0f*TotalCorrect/NumberOfTimes;

Then, using %f:

printf("%f percent\n", percent); // "80.000000 percent"

Note that this will display the percentage out to many decimal places; if you want a cleaner display without a decimal point, you could just calculate the percent as an int:

// multiply before dividing to avoid integer division problems
int percent = 100*TotalCorrect/NumberOfTimes;
printf("%d percent\n", percent); // "80 percent"

Hope this helps!