xin - 1 year ago 129
C Question

C program: Simple math program

Want to print for example
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:
-7446528 percent

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

``````# include <stdio.h>

int main()
{
int i,a,b,c,d,e,f,g;
float percent;

printf("\n");
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);
printf("\n");
srand(time(NULL));
//Random number generator
for (i=0;i<NumberOfTimes;++i)
{
b = rand() %3 + 1;
c = rand() %3 + 1;
a = rand() %2 + 1;

if (a == 1)
{
printf("%d + %d = ", b,c);
d = b + c;
{
printf("  +Correct\n");
}
//Random subtraction problems
else
{
printf("  +Wrong, it was %d\n", d);
}
}
if (a == 2)
{
printf("%d - %d = ", b,c);
scanf("%d", &SubAns);
g = b - c;
if (SubAns == g)
{
printf("  +Correct\n");
SubCorrect = SubCorrect + 1;
}
else
{
printf("  +Wrong, it was %d\n", g);
SubIncorrect = SubIncorrect + 1;
}
}
}
//Producing the output to wrong/right numbers and grade percentage
printf("\n");
printf("\n");
percent=NumberOfTimes/TotalCorrect;
printf("%d percent \n", percent);
return 0;
}
``````

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

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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download