Float返回0

时间:2013-09-23 04:12:38

标签: c

编辑#3:所以当我用gcc编译时,一切正常。如果我使用clang(版本3.0),它只给我0。我很困惑为什么clang不适用于此,因为它似乎相对简单。

编辑#2:好的,所以我已经确认感谢大家代码确实有效,但它可能就是环境。我正在使用ARM三星Chromebook在Ubuntu上做这一切(实际上是通过chroot)。我正在使用clang 3.0(只有-o标志)来编译所有内容。我在vim中输入所有内容。是因为我在ARM上发生了这种情况吗?

我一直盯着这看了两个小时,无法理解我的错误。无论我做什么,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;
}

1 个答案:

答案 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);
}