-1

我对 c 中的 pow 函数有疑问。变量 Qb 将给出错误的输出 - 它给出 10000 而不是 177827.941004 导致最终输出为 2007 而不是 2009

编译命令是按。 gcc -ggdb -std=c99 -Wall -Werror -o test_pow02 test_pow02.c -lm

#include <stdio.h>
#include <math.h>

int main(int argc, char **argv)
{
    int my_rating = 2000;
    int opponent_rating = 2100;
    int coeff = 15;
    int score = 1;
    int new_rating;

    double Qa = pow(10, my_rating / 400); // 100000
    double Qb = pow(10, opponent_rating / 400); // 177827.941004

    double Ea = Qa / (Qa + Qb); 

    new_rating = my_rating + ( (score - Ea) * coeff );

    printf("Qa is %g\n", Qa);
    printf("Qb is %g\n", Qb);
    printf("New Rating is %d\n", new_rating);

    return 0;
}

但如果我将 2100/400 硬编码为 5.25,它将正常工作。最后我已经有了 -lm 。我该如何解决?

#include <stdio.h>
#include <math.h>

int main(int argc, char **argv)
{
    int my_rating = 2000;
    //int opponent_rating = 2100;
    int coeff = 15;
    int score = 1;
    int new_rating;

    double Qa = pow(10, my_rating / 400); // 100000
    double Qb = pow(10, 5.25); // 177827.941004

    double Ea = Qa / (Qa + Qb); 

    new_rating = my_rating + ( (score - Ea) * coeff );

    printf("Qa is %g\n", Qa);
    printf("Qb is %g\n", Qb);
    printf("New Rating is %d\n", new_rating);

    return 0;
}
4

1 回答 1

3

运算pow(10, opponent_rating / 400);不等于177827.941004

opponent_rating / 400 == 5    

涉及两个整数的操作将产生一个整数,
在这种情况下,结果5.25被剪裁为5

您应该用双精度除以得到在pow函数opponent_rating / 400.0中使用的双精度结果。

于 2013-06-12T14:57:28.233 回答