PHP,如何遍历数字并在我们前进和计算新数字时添加


php, how to iterate through numbers and add as we go along and calculate new numbers

我写了一个简单的代码来计算数学方程,但我想从$start迭代数字到$end。我正在制作一个游戏,此页面将计算达到下一个级别并将其插入数据库所需的经验量。从$start迭代到$end并计算该级别所需的exp量的最佳方法是什么?

法典:

<?php 
    $start = 1;
    $end = 100;
    $level = $start++;
    $l = $level - 1;
    $exp = ((40*($l * $l)) + (360 * $l)); 
?>

当它现在坐着时,它会计算第一级,但我一生都无法弄清楚如何让它通过直到它达到$end

$exp = 0;
for($level = $start; $level <= $end; $level++){
    $exp += 40 * $l ** 2 + 360 * $l;
}

实际上,我们可以使用数学通过概括所需的经验水平来加快速度。由于您的体验函数是二次函数的总和:

  f(n)
= S[1 100] 40n^2 + 360n
= 40n (n + 1) (2n + 1) / 6 + 360n (n + 1) / 2

在 PHP 中:

40 * $level * ($level + 1) * (2 * $level + 1) / 6 + 360 * $level * ($level + 1) / 2

或者如果您愿意,可以进一步简化它。

这绝对比计算循环 100 次要快。

如果$start不是 1,只需使用 f(end) - f(start - 1)

您必须计算每个级别所需的 xp,因此您应该将计算代码放入一个循环中,该循环从最低级别开始,一直持续到达到最高限制/结束级别。您可以在 PHP 中选择两种不同的循环类型,for 循环和 while-loop。

就个人而言,我会为这个特定的"问题"选择 while-loop,但这是每个人都必须自己决定的事情。计算器的代码如下所示:

 // Create an extra variable to store the level for which you are currently calculating the needed xp 
 $i = $start;
 // The while-loop (do this code until the current level hits the max level as specified)
 while($i <= end) {
    // use $i to calculate your exp, its the current level
    // Insert code here...
    // then add 1 to $i and do the same again (repeat the code inside loop)
    $i++;
 }

以下是一些指向 php 文档的链接:

while-loop(同时循环
)for 循环