想打印例如 等级:4/5 80% 程序询问用户他们想要解决多少数学问题并打印出错误的数量/权利的数量"和他们的成绩。我想我在代码的最后没有我的数学因为它的打印输出例如: 等级:4/5 -7446528%
+++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++
# 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("\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;
//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
else
{
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;
}
else
{
printf(" +Wrong, it was %d\n", g);
SubIncorrect = SubIncorrect + 1;
}
}
}
//Producing the output to wrong/right numbers and grade percentage
TotalCorrect = AddCorrect + SubCorrect;
printf("\n");
printf("Grade: %d/%d\n",TotalCorrect,NumberOfTimes);
printf("\n");
percent=NumberOfTimes/TotalCorrect;
printf("%d percent \n", percent);
return 0;
}
答案 0 :(得分:3)
有一些事情正在发生。首先,要使用float
打印printf
,请使用%f
。 %d
用于int
s。
其次,当你计算percent
时,你会意外地使用整数除法。由于NumberOfTimes
和TotalCorrect
都是整数,NumberOfTimes/TotalCorrect
执行整数除法并生成int
。在评估整个初始化表达式之后,它只转换为float
。请改用:
percent = (float)TotalCorrect / NumberOfTimes;
// OR, if you want an actual percent:
percent = 100.0f*TotalCorrect/NumberOfTimes;
然后,使用%f
:
printf("%f percent\n", percent); // "80.000000 percent"
请注意,这会显示多个小数位的百分比;如果您想要一个没有小数点的清洁显示,您可以将百分比计算为int
:
// multiply before dividing to avoid integer division problems
int percent = 100*TotalCorrect/NumberOfTimes;
printf("%d percent\n", percent); // "80 percent"
希望这有帮助!
答案 1 :(得分:1)
在C中,除非指向浮点数,否则除以两个整数将不会得到浮点数。这就是语言的运作方式。你必须将NumberOfTimes和TotalCorrect强制转换为浮点数。
所以更换
percent=NumberOfTimes/TotalCorrect;
与
percent=(float)TotalCorrect/(float)NumberOfTimes * 100;
此外,您尝试在行
中打印一个整数浮点数printf("%d percent \n", percent);
这给你一个不稳定的结果。相反,尝试:
printf("%d percent \n", (int)percent);