我正在尝试制作此前端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循环。
您可以采用数值方法,但是您陷入了浮点运算的陷阱(浮点运算是否被破坏了?),并且得到了一个与给定值不匹配的数字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));
嘿@Nina,首先非常感谢您的答复,其次,不幸的是,这对我而言并不奏效,因为它在所有数字上都是动态的,仅适用于我在问题中给出的示例,但是我感谢您的努力,现在可以你做同样的事情,但所有数字都是动态的,因为我尝试了几件事,我尝试在你写的第二个代码片段中将42更改为24,这对某些数字如3.15和2.15起作用,这是正确的6.06,但是当我再次将其更改为3.22,而将其更改为6.18,则不是这样。我将继续发表其他评论
我还尝试了一些事情,并添加了一些代码
function sumD(a, b) { function getValue(v) { return +(v.toString().match(/\.(\d*)/)[1] || '').padEnd(2, 0); } var i = Math.floor(a + b), p = getValue(a) + getValue(b); var test = Math.fround((a + b) - i); var x = getValue(test); var strr = toString(x).length -2; var y = parseInt(('1'.toString()).padEnd(strr, '0')); var z = Math.floor(x / y); if (p > 23) { p -= z; ++i; } return i + p / 100; } console.log(sumD(3.22, 2.2));
,并且对某些数字起作用,所以叫idk。对不起,代码混乱。应该
4.2
是2
或20
为地方呢?如果您的意思是小数点后的浮点数,那么应该是2而不是20。
为什么
6.18
错了?