Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用C语言编写的RuneScape体验数学公式_C_Math_Formula - Fatal编程技术网

用C语言编写的RuneScape体验数学公式

用C语言编写的RuneScape体验数学公式,c,math,formula,C,Math,Formula,我试图用C语言实现一个数学公式,计算特定Runescape级别所需的XP,但我没有得到正确的输出。等级1给出“75”经验值,等级99给出“11059837”。我的实现有什么问题?我想不出来。以下是我写的: #include <stdio.h> #include <math.h> int main() { /* Determines the XP needed for a Runescape Lv */ int lv; printf("Enter

我试图用C语言实现一个数学公式,计算特定Runescape级别所需的XP,但我没有得到正确的输出。等级1给出“75”经验值,等级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;
}
#包括
#包括
int main(){
/*确定Runescape Lv所需的XP*/
int-lv;
printf(“输入Lv(1-99):”;
scanf(“%d”和&lv);
如果(lv>99 | | lv<1){
printf(“无效Lv”);
}否则{
int xp=0;
int输出=0;
int i;

对于(i=1;i让我们用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
会使常数变为双精度。将整数
i
除以双精度是根据隐式转换规则进行的,该规则被理解为具有双精度结果的浮点运算。
pow()
本身就是双精度函数,因此表达式的其余部分按设计工作

通过此更改,级别99给出14391 160

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


诀窍:如果有疑问,在一个数学公式中,当混合
int
float
double
时,您也可以显式地将其转换为正确的类型,例如
(double)i/7

我猜是
pow(2,(i/7))中的整数除法
。你确信这个公式是整数数学吗?除非他们使用浮点…(例如在
i/7
中),否则对floor没有任何意义。你调用floor,但用int做所有的数学运算。我不认为这是你的问题,但因为你链接到的方程中的总和有一个上限“level-1”,您应该有一个类似这样的
for循环,而不是:
for(i=1;i
您应该将变量
i
强制转换为
float
,如
pow(2,((float)i/7))