温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - application spits the numbers back at me even though it should return another value
javascript

javascript - 应用程序将数字吐给我,即使它应该返回另一个值

发布于 2020-03-27 15:51:27

我正在尝试制作此前端Web应用程序,在该应用程序中,您将以这种形式(例如3.22)在提示中提供英亩和克拉,并进行计算并在chrome JS控制台中将其总计

例如,您有3.22英亩的土地,而另一块土地是2.2英亩。如果您得到这些数字的总和,应该给您5.42,不,我希望它们返回6,因为英亩有24克拉,如果您计算3英亩和22克拉+ 2英亩和2克拉,它应该给您6英亩,那就是我在这里尝试做的。我整夜都在尝试,每次在提示符下输入的数字在控制台中吐给我时,这是我的代码:

window.setTimeout(function() {
var acres = [];
var floats = [];
var wholes = [];
var input = prompt("What would you like to do?");
while (input !== "quit") {
    if (input === "total") {
        console.log("***********");
        acres.forEach(function(total, i) {
            console.log(i + ": " + total);
        })
        console.log("***********");
    } else if (input === "calc") {
        var num = prompt("Please enter a number");
        while (num !== "back") {
            if (num === "back") {
                break;
            }
            acres.push(num);
            var ftotal = 0
            var wtotal = 0;
            floats = [];
            wholes = [];
            for(var i = 0; i < acres.length; i++) {
                alert("entered the for loop");
                var acresNum = acres.pop();
                var str = acresNum.toString();
                var number = Math.floor((str).split(".")[1]);
                floats.push(number);
                ftotal += floats[i];
                //-------------------------
                var num2 = Math.floor(acresNum);
                wholes.push(num2);
                wtotal += wholes[i];
            }
            alert("exited the for loop");
            console.log(ftotal);
            console.log(wtotal);
            if (ftotal > 23) {
                wtotal++;
            }
            acres.push(wtotal + "." + ftotal);
            var num = prompt("Please enter a number");
        }
    }
    var input = prompt("What would you like to do?");
}
console.log("OK, YOU QUIT THE APP");}, 500)

该应用程序的整体逻辑在于该else if(input === "calc")区域中的for循环

此图像显示了在控制台中输入的数字

查看更多

查看更多

提问者
Ali Mohamed
被浏览
18
Nina Scholz 2020-02-01 03:03

您可以采用数值方法,但是您陷入了浮点运算的陷阱(浮点运算是否被破坏了?),并且得到了一个与给定值不匹配的数字42

function sum(a, b) {
    var s = a + b,
        i = Math.floor(s),
        p = (s - i) * 100;

    console.log(p);
    if (p >= 42) { // never reached
        p -= 42;
        ++i;
    }
    return i + p / 100;
}

console.log(sum(3.22, 2.2));

作为解决方案,您可以将位置分开为字符串,并添加整数值,然后检查该值是否大于一英亩,然后返回调整后的值。

function sumD(a, b, threshold) {
    return [a, b]
        .map(v => v.toString().split('.'))
        .reduce((r, a) => {
            a.forEach((v, i) => r[i] += +v);
            r[0] += Math.floor(r[1] / threshold);
            r[1] %= threshold;
            return r;
        }, [0, 0])
        .join('.');			
}

console.log(sumD(3.22, 2.2, 24));