【问题标题】:Math returns wrong answers [duplicate]数学返回错误答案[重复]
【发布时间】:2013-12-31 07:57:04
【问题描述】:

我已经尝试了将近一个小时来完成这项工作,但它一直在逃避我。

public static function npcBattleStats($npc) {
    $npc = self::findNPC($npc);
    $rand = mt_rand(1.2, 3.3);
    $npcStats['attack'] = (($npc['level'] * $npc['power']) / $rand);
    $npcSpeeda = round($npc['power'] / 2.4);
    $npcSpeedb = round(($npc['power'] / 1.1) + 2);
    $npcStats['speed'] = mt_rand($npcSpeeda, $npcSpeedb);
    return $npcStats;
}

level = 3 | power = 50
$npcStats['attack'] = (($npc['level'] * $npc['power']) / $rand);

其他一切似乎都正常工作,但攻击一直处于关闭状态。它应该在 45 到 115 之间,但只返回以下值。

[attack] => 50 | [attack] => 150 | [attack] => 75

我希望我不会在这里遗漏一些简单的东西,但我们将不胜感激。

【问题讨论】:

  • 第一个错误:mt_rand 期望并返回整数。所以你基本上要求并获得一个介于 1 和 3 之间的 int,包括 1 和 3。
  • @cHao - 不幸的是 rand() 似乎以同样的方式工作。有没有更好的方法来获取它们之间的随机数?
  • ^ 尝试使用$rand = mt_rand(1.2*10, 3.3*10)/10;
  • 我无法理解 150 / (1.3 -> 3.3) 应该如何返回 15 到 42 之间的值。150/3.3 = 45.45 rep - 所以这里的最小范围是 45.45 -> 115.38
  • @RUJordan - 我对这些值的数学计算有误。我最初只是在计算器上除以 50。我相应地编辑了我的帖子

标签: php math


【解决方案1】:

Funktion mt_rand() 似乎只吐出 aut 整数,而不是浮点数。试试这个:

$rand = mt_rand(12, 33) / 10;

【讨论】:

  • 谢谢。我没有意识到它只适用于整数。这非常有效!
  • 不客气。那么请接受这个答案;-)
【解决方案2】:

首先正如 cHao 所说 PHP 手册:“返回值:一个介于 min(或 0)和 max(或 mt_getrandmax(),含)之间的随机 整数 值,如果 max 小于 min,则为 FALSE。”

要修复它,你需要这样的东西

$rand = mt_rand(35, 100) / 10;
//35 is your max
//120 is your low

所以当你得到: 你的最大值:

(5 * 50) / 3.5 = 42.85.. //so round it

你的低谷:

(5 * 50) / 10 = 15

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 2014-12-04
    • 1970-01-01
    相关资源
    最近更新 更多