【发布时间】:2019-03-04 16:48:52
【问题描述】:
我正在尝试完成一个程序,该程序显示小数点(作为百分比),其中一副牌中的钻石、梅花、红心或黑桃将被抽出 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
对于这篇长文深表歉意,但如果能帮助我解决这个问题,我将不胜感激,因为这是我完成这个程序唯一需要解决的问题。谢谢!
【问题讨论】:
-
请学习如何正确缩进你的代码。
-
为什么要在同一个范围内缩进代码?
-
您应该考虑使用一个包含 4 个(甚至 5 个)条目的数组来记录数字。它会将您的开关折叠成一条语句,然后您使用循环来打印结果。当然,您需要一组合适的西装名称。
-
我不是故意这样缩进我的代码,我只是想把它与文本分开,当我将它标记为 C 问题时,它以这种方式缩进。如果给您带来不便,我们深表歉意。 Aprogrammer 解决了我的问题并且程序正在运行。感谢您的评论。
标签: c