简体   繁体   English

为什么这个php数学代码无法正常工作

[英]Why isn't this php math code working

I am trying to convert this as3 code to php but its not working correctly. 我正在尝试将此as3代码转换为php,但无法正常工作。 I need it like the as3 one generating thanks! 我需要像as3一样产生感谢!

PHP: PHP:

print(floor(rand() * 1000) + 3000);

Result:28240000 结果:28240000

AS3: AS3:

var intCID = Math.floor(Math.random() * 1000) + 3000;
var strSessionId = String(intCID);
trace(strSessionId);

Result:3330 结果:3330

PHP's rand() function gives you a random integer value, not a float (decimal) value. PHP的rand()函数为您提供一个随机的整数值,而不是浮点(十进制)值。 Therefore you get this real big value if you do * 1000 因此,如果您* 1000,您将获得此真正的大价值

Be sure to check the PHP manual's rand() function. 确保检查PHP手册的rand()函数。 You will see that you can set the min and max value for generated random numbers, like rand(1, 1000) 您会看到可以为生成的随机数设置最小值和最大值,例如rand(1, 1000)

Hope this help generating your intended values. 希望这能帮助您产生预期的价值。

You are calling rand() without argument, and according to docs: 您正在调用不带参数的rand() ,并且根据docs:

if called without the optional min, max arguments rand() returns a pseudo-random integer between 0 and getrandmax() 如果在没有可选min的情况下调用,则max参数rand()返回介于0和getrandmax()之间的伪随机整数

so you should use this instead : 所以你应该改用这个:

rand(0,1000)

Description 描述

int rand ( void ) 整数rand(void)

int rand ( int $min , int $max ) 整数rand(整数$ min,整数$ max)

If called without the optional min, max arguments rand() returns a pseudo-random integer between 0 and getrandmax(). 如果在没有可选min的情况下调用max参数,则rand()会返回介于0和getrandmax()之间的伪随机整数。 If you want a random number between 5 and 15 >(inclusive), for example, use rand(5, 15). 例如,如果要5到15之间的一个随机数>(含),请使用rand(5,15)。

Source: http://php.net/manual/en/function.rand.php 资料来源: http : //php.net/manual/en/function.rand.php

Use: rand(0,1) to get the same result 使用: rand(0,1)得到相同的结果

您的AS3代码会生成3000到4000之间的随机数,因此PHP中的等价项为:

$rand = rand(3000, 4000);

In PHP, rand() returns a value from 0 to getRandMax() which is often 32767, and is integer, so the call to PHP rand() should be emulated as this AS3 code: 在PHP中, rand()返回从0到getRandMax()的值,该值通常为32767,并且是整数,因此对PHP rand()的调用应模拟为以下AS3代码:

Math.floor(Math.random()*32768) // returns 0..32767 as integer

The PHP code rand($min,$max) is emulated by the following: PHP代码rand($min,$max)通过以下方式进行仿真:

Math.floor(Math.random()*(1+max-min))+min

But, by all means do NOT expect that both PHP and AS3 code will return the exact same value. 但是,绝对不要期望PHP和AS3代码都将返回完全相同的值。

您应该使用更好的 (性能明智) mt_rand()

var_dump( mt_rand(3000, 4000) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM