gpt4 book ai didi

c - 在C中循环后显示十进制值作为结果

转载 作者:行者123 更新时间:2023-12-02 09:08:39 24 4
gpt4 key购买 nike

我正在尝试完成一个显示小数(作为百分比)的程序,其中从 1000 次中抽出一副牌中的方 block 、梅花、红心或黑桃。这是我完成的代码:

#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

到目前为止,我已尝试通过将结果声明为 float 并将每次绘制中计算的频率除以 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

对长篇文章表示歉意,但我希望能得到任何帮助来解决这个问题,因为这是我完成这个程序唯一需要解决的问题。谢谢!

最佳答案

问题是像 res1= freq1/1000 这样的东西首先被计算为整数,因为两个参数都是整数,然后转换为 float 。请改用 res1= freq1/1000.0 之类的内容,以便至少有一个参数是浮点型,第二个参数将自动转换为浮点型。

关于c - 在C中循环后显示十进制值作为结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54987852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com