我正在尝试用 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;
}
数学公式为:
最佳答案
让我们用级别 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 ,结果是正确的(如果您将输出理解为进入下一级别所需的经验值)。
窍门:如果有疑问,在数学公式中,混合 int
和 float
或 double
,您也可以显式转换为正确的类型,例如 (double)i/7
。
关于c - 用于 RuneScape 体验的 C 数学公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28994618/