【问题标题】:Use PHP To Generate Random Decimal Beteween Two Decimals使用 PHP 生成两个小数之间的随机小数
【发布时间】:2012-05-12 06:24:23
【问题描述】:

我需要生成一个随机数,到 PHP 中 2 位小数之间的第 10 位。

例如。介于 1.2 和 5.7 之间的兰特数。它将返回 3.4

我该怎么做?

【问题讨论】:

  • 这很愚蠢,但我需要一个函数。如下: function drand($low, $high) { return mt_rand($low*100, $high*100) / 100; }

标签: php random


【解决方案1】:

更通用的解决方案是:

function count_decimals($x){
   return  strlen(substr(strrchr($x+"", "."), 1));
}

public function random($min, $max){
   $decimals = max(count_decimals($min), count_decimals($max));
   $factor = pow(10, $decimals);
   return rand($min*$factor, $max*$factor) / $factor;
}

$answer = random(1.2, 5.7);

【讨论】:

  • 对于那些追求这个解决方案的人来说,现在更好的方法是将 count_decimals() 函数作为闭包嵌入到 random() 中,因此它在全局范围内是隐藏的。
【解决方案2】:

你可以使用:

rand ($min*10, $max*10) / 10

甚至更好:

mt_rand ($min*10, $max*10) / 10

【讨论】:

  • fwiw - 从 php 7.1 开始,rand 是 mt_rand 的别名
【解决方案3】:

你可以这样做:

rand(12, 57) / 10

PHP 的随机函数允许您只使用整数限制,但您可以将生成的随机数除以 10。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 2014-06-23
    • 2014-12-19
    • 2014-10-02
    相关资源
    最近更新 更多