c - 用于 RuneScape 体验的 C 数学公式

标签 c math formula

我正在尝试用 C 语言实现一个数学公式来计算特定 Runescape 级别所需的 XP,但我没有得到正确的输出。 1 级给出“75”XP,99 级给出“11059837”。我的实现有什么问题吗?我想不通。这是我写的:

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

int main() {
    /* Determines the XP needed for a Runescape Lv */
    int lv;
    printf("Enter a Lv(1-99): ");
    scanf("%d", &lv);

    if(lv > 99 || lv < 1) {
        printf("Invalid Lv");
    } else {
        int xp = 0;
        int output = 0;

        int i;
        for(i = 1; i <= lv; i++) {
            xp += floor((i + (300 * (pow(2, (i/7))))));
        }
        output = floor((xp/4));
        printf("The amount of XP needed for Lv%d is %d\n", lv, output);
    }

    return 0;
}

数学公式为:formula

最佳答案

让我们用级别 1 做一个简单的测试。

1/7 is 0.14... 
2 to the power of (1/7) is 1.104...
times 300, we obtain 331.2...
add 1 and take the integer part, you'll obtain 332 which divided by 4 taking the integer part is 83

根据这个公式的输出应为83。

问题是i被定义为int,而7是一个int常量。 C的转换规则,使编译器将其理解为整数除法,并得到整数结果:

integer division of 1 by 7 is 0 (remains 1)
2 to the power of 0 is always 1.  
times 300 is 300
add 1 and take the floor you obtain 301, which divided by 4 taking the integer part is 75, the value that you've found. 

如何解决这个问题?稍微改变一下你的表情:

        xp += floor((i + (300 * (pow(2, (i / 7.0))))));

写入 7.0 使常量成为 double 型。将整数 i 除以 double 是根据隐式转换规则理解为具有 double 结果的浮点运算。 pow() 本身就是一个 double 函数,因此表达式的其余部分按设计工作。

通过此更改,级别 99 给出 14 391 160。

根据this table ,结果是正确的(如果您将输出理解为进入下一级别所需的经验值)。

窍门:如果有疑问,在数学公式中,混合 intfloatdouble,您也可以显式转换为正确的类型,例如 (double)i/7

关于c - 用于 RuneScape 体验的 C 数学公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28994618/

相关文章:

c - 读取 C 结构中的浮点值时出错

c# - 在 .NET 中识别替代日期(在 PowerShell、C# 或 VB 中)

c++ - GCC 中 cmath 的 pow() 的正确性

javascript - 文本区域计算

excel - 我在 A 列中有一些地址格式不正确,我想将状态复制到单独的单元格中

excel - Excel中如何从MIN公式中排除0

c - getaddrinfo 未获取 ipv6 地址

c++ - 字符串与最相似的字符串比较

vba - Excel年周组合计算

c - 如何在 C 语言中将十六进制值保存为字符?