gpt4 book ai didi

javascript - 随机数生成器,小数中断

转载 作者:行者123 更新时间:2023-11-29 10:50:56 25 4
gpt4 key购买 nike

这是我的代码:

    var randomNumber = function(from,to,dec)
{
var num = Math.random()*(to-from+1)+from;
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return result;
};

目标是获取给定范围内的随机数,并将结果四舍五入到给定的小数位。它适用于 1-10 或 50-100 之类的范围,但是当我尝试这样的小数字时:

randomNumber(0.01,0.05,5)

我得到了不好的结果,例如 0.27335 和 1.04333。

最佳答案

您的计算结果勉强 +1。应该是没有 +1 的 to-from:

var randomNumber = function (from, to, dec) {
var num = Math.random() * (to - from<s> +1</s>) + from;
var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
return result;
};

您的代码应如下所示:

var randomNumber = function (from, to, dec) {
var num = Math.random() * (to - from) + from;
var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
return result;
};

实际上,可以通过省略 result 变量来进一步缩短,如下所示:

var randomNumber = function (from, to, dec) {
var num = Math.random() * (to - from) + from; //Generate a random float
return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec); //Round it to <dec> digits. Return.
};

关于javascript - 随机数生成器,小数中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10481007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com