我一直盯着这看了两个小时,无法理解我的错误。无论我做什么,Float似乎都会返回0.000000。我试过除以10000.0,将10000存储在float类型的变量中,类型为double。
我甚至编写了一个小程序,它只有一个float类型的变量,存储了1.1,然后是printf(“%f”,变量),打印的是0.000000。
编辑:忘记提到1.1就在那里,因为我只是测试浮动..我知道我必须除以10000,哈哈。我做错了什么?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
bool diceRoll (int a)
{
int n = 0;
int b = 0;
while(n < 1) {
b = rand() % 12;
if(b == a || b == 6) n++;
}
if(b == 6) return false;
else return true;
}
int main (void)
{
srand( (unsigned)time(NULL));
int a, n, house, player;
float houseWinRate, playerWinRate;
house = 0;
player = 0;
float total = 1.1;
for(n = 0; n < 10000; n++) {
a = rand() % 12;
if(a == 1 || a == 2 || a == 11) {
house++;
}
else if(a == 6 || a == 10) {
player++;
}
else {
if(diceRoll(a) == true) player++;
else house++;
}
}
printf("%i, %f\n", house, total);
houseWinRate = house / total;
playerWinRate = player / total;
printf("The house has %i points. That's a winrate of %f.\n", house, houseWinRate);
printf("The player has %i points. That's a winrate of %f.\n", player, playerWinRate);
return 0;
}
答案 0 :(得分:3)
[已解决] OP已验证此代码可在Chromebook上使用gcc。
这不是答案,但此处的内容无法发布到评论中。
您可以在*100
之前尝试/total
吗? (指你的codepad code)
还可以尝试使用最简单的测试应用程序来仅测试算术部分(也使用houseWinRate
的双精度):
int main (void)
{
// using hardcoded value here
int house = 5492;
int player = 4508;
double houseWinRate = 0.0;
float playerWinRate = 0.0;
float total = 10000.0;
houseWinRate = ((double)house / total) * 100.0;
playerWinRate = (player * 100.0) / total;
printf("[double] The house has %i points. That's a winrate of %lf percent.\n", house, houseWinRate);
printf("[mul first] The player has %i points. That's a winrate of %f percent.\n", player, playerWinRate);
}