扫码关注官方订阅号
比如我想用 Math.random() 取 -20~-10 和 10~20 这两个范围的随机数,有什么最有精简的解决方案吗?比如不用 if 语句能不能做到?谢谢大家解惑。
(Math.floor(Math.random() * (20 - 10 + 1)) + 10) * (Math.random() < 0.5 ? -1 : 1)
function getRandom(min,max){ return Math.random()*(max-min)+min; }
Math.random() * (max - min) + min;
详见
修改:
(Math.random() * (max - min) + min)*(Math.random()<0.5?1:-1);
function rand(min, max) { if ( min >= max ) { return; } return Math.floor(min + (max - min+1) * Math.random()); }
这是取一个范围内整数的
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
扫描下载App
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
详见
修改:
这是取一个范围内整数的