gpt4 book ai didi

Javascript : function checking if the answer to score as a percentage has more than 2 decimal places

转载 作者:行者123 更新时间:2023-11-29 20:01:57 25 4
gpt4 key购买 nike

我想为我的学生创建一个动态工作表,这样他们每次创建时都会看到不同的问题。我正在尝试创建的问题,即如果我在总 Y 中得到 X,则计算百分比。

这是一起工作的 3 个函数,第一个生成一些数字,调用第二个,然后调用第三个来检查它是否超过 2 个小数位,如果是,第二个创建一个新的 SCORE 数字重复直到找到小数点后 2 位或更少的答案,然后返回适用于第一个的 SCORE 数字,输出它。

我不断收到以下三种输出之一:未定义 SCORE 应在的位置、根本没有输出或一个工作问题。

有时我无法理解它是如何工作的,有时会抛出 undefined 而在其他时候则完全没有给出。

任何想法。

function scorePercent()
{
var output="";
var total = Math.floor((Math.random()*99)+1);
var score = Math.floor((Math.random()*(total-1))+1);
output = output + "<div>A score of " + chkScore(score,total) + " out of " + total + ".</div></br>";

document.getElementById("qOut").innerHTML=output;

}

function chkScore(n1,n2)
{
var answ = (n1/n2)*100;
if(dps(answ)>2)
{
var scoreNew = Math.floor((Math.random()*(n2-1))+1);
chkScore(scoreNew, n2);
}
else
{
return n1;
}
}

function dps(num)
{
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(
0,
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0)
// Adjust for scientific notation.
- (match[2] ? +match[2] : 0));
}

最佳答案

您的 chkScore 中有一个递归函数,但您没有返回-ing 来自“更深层次”迭代的结果。

试试这个:

function chkScore(n1,n2){
var answ = (n1/n2)*100;
if(dps(answ)>2) {
var scoreNew = Math.floor((Math.random()*(n2-1))+1);
return chkScore(scoreNew, n2); // <-- return that.
} else {
return n1;
}
}

那里缺少return,导致函数有时不返回任何东西。

“更深层次”的迭代只会返回它们的值向上 1 个“级别”,所以“级别”必须通过它,如果你明白我的意思的话。

关于Javascript : function checking if the answer to score as a percentage has more than 2 decimal places,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13931127/

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