我正在尝试完成一个显示小数点(以百分比表示)的程序,从中抽取1000张卡片中的钻石,球杆,心形或小铲形。这是我完成的代码:
#include <stdio.h>
int main()
{
unsigned int freq1 = 0;
unsigned int freq2 = 0;
unsigned int freq3 = 0;
unsigned int freq4 = 0;
for (unsigned int draw = 1; draw <= 1000; ++draw) {
int face = 1 +rand() % 4;
switch (face) {
case 1:
++freq1;
break;
case 2:
++freq2;
break;
case 3:
++freq3;
break;
case 4:
++freq4;
break;
}
}
printf("Percent of diamonds is %u\n", freq1);
printf("Percent of clubs is %u\n", freq2);
printf("Percent of hearts is %u\n", freq3);
printf("Percent of spades is %u\n", freq4);
}
当我运行代码时,它将获得1000个正确的绘制数值。这是输入:
Percent of diamonds is 249
Percent of clubs is 252
Percent of hearts is 258
Percent of spades is 241
我正在尝试让程序从这些数字中输入计算出的十进制值,例如:
Percent of diamonds is 0.25
到目前为止,我已经尝试通过将结果声明为浮点数并将每次绘图中计算出的频率除以1000来纠正此问题,以便结果将是我尝试显示的十进制值。这是我尝试的代码:
#include <stdio.h>
int main()
{
unsigned int freq1 = 0;
unsigned int freq2 = 0;
unsigned int freq3 = 0;
unsigned int freq4 = 0;
float res1, res2, res3, res4;
for (unsigned int draw = 1; draw <= 1000; ++draw) {
int face = 1 +rand() % 4;
switch (face) {
case 1:
++freq1;
break;
case 2:
++freq2;
break;
case 3:
++freq3;
break;
case 4:
++freq4;
break;
}
}
res1= freq1/1000;
res2= freq2/1000;
res3= freq3/1000;
res4= freq4/1000;
printf("Percent of diamonds is %.2f\n", res1);
printf("Percent of clubs is %.2f\n", res2);
printf("Percent of hearts is %.2f\n", res3);
printf("Percent of spades is %.2f\n", res4);
}
但是,当我尝试运行它时,最终得到了以下结果输入:
Percent of diamonds is 0.00
Percent of clubs is 0.00
Percent of hearts is 0.00
Percent of spades is 0.00
很长的歉意,但是我很乐意帮助您解决此问题,因为这是我完成该程序所需解决的唯一事情。谢谢!
答案 0 :(得分:5)
问题在于,res1= freq1/1000
之类的东西首先被计算为整数,因为两个参数都是整数,然后转换为浮点数。请改用res1= freq1/1000.0
之类的东西,以使至少一个参数是浮点数,第二个参数将自动转换为浮点数。