所以我用html和javascript创建了这个简单的网站,用户输入他们的零钱并将其全部转换为最终的金额。由于一些非常奇怪的原因,当镍和硬币是一定数量时,会添加大量小数位,例如当镍是8时。即使这些小数位不是那样,总量也有很长的小数位。由于所有计算都不应超过2位小数,因此我有点难过。对于我将在代码中看到的解决方案,我只是将数字四舍五入,因为这个页面用于编程课程而不是数学课程,我认为这对于作业来说并不重要,但我很好奇为什么这样做正在发生的事情,如果我将来创造一些严肃的东西,我可以避免这种类型的问题。
您可以在此处查看此代码,http://192.236.14.50/part4/
单击Change Converter并输入值并点击转换。如果你打开了javascript控制台,你会看到我在说什么。以下是javascript代码。
function registerList3() {
img = document.getElementById("moneyButton");
img.addEventListener("click", function() { calculateMoney(); }, false);
}
// Function calculateMoney tallies up all the change inputs and calculates the total
function calculateMoney() {
// Create the various var's for each input and assign to their values.
var pennies = document.getElementById("pennies").value;
var nickels = document.getElementById("nickels").value;
var dimes = document.getElementById("dimes").value;
var quarters = document.getElementById("quarters").value;
var loonies = document.getElementById("loonies").value;
var toonies = document.getElementById("toonies").value;
console.log("Pennies " + pennies);
console.log("Nickels " + nickels);
console.log("Dimes " + dimes);
console.log("Quarters " + quarters);
console.log("Loonies " + loonies);
console.log("Toonies " + toonies);
// Multiply pennies amount by 0.01.
var penniesAmount = parseFloat(pennies * 0.01);
// Multiple nickels amount by 0.05.
var nickelsAmount = parseFloat(nickels * 0.05);
// Multiple dimes amount by 0.1.
var dimesAmount = parseFloat(dimes * 0.1);
// Multiple quarters amount by 0.25.
var quartersAmount = parseFloat(quarters * 0.25);
// Loonies amount equals itself, no multiplication needed.
var looniesAmount = parseFloat(loonies);
// Multiple toonies amount by 2.
var tooniesAmount = parseFloat(toonies * 2);
console.log("-----AMOUNTS-----");
console.log("Pennies " + penniesAmount);
console.log("Nickels " + nickelsAmount);
console.log("Dimes " + dimesAmount);
console.log("Quarters " + quartersAmount);
console.log("Loonies " + looniesAmount);
console.log("Toonies " + tooniesAmount);
// Create totalAmount var, equal to all amounts added together.
var totalAmount = penniesAmount + nickelsAmount +
dimesAmount + quartersAmount + looniesAmount + tooniesAmount;
console.log("Total Amount " + totalAmount);
// If the total amount is not a number (NaN)...
if (isNaN(totalAmount)) {
// Change total label to 0.
document.getElementById("totalMoney").innerHTML = 0;
// Alert user to input only numbers.
alert("Please enter numbers only");
}
// Else if total amount is a number...
else {
// Create rounded amount and round total amount to 2 decimal places.
// Shouldn't be neccessary, but it is. See notes above.
var roundedAmount = Math.round(totalAmount * 100) / 100;
// Change total money label to rounded amount.
document.getElementById("totalMoney").innerHTML = roundedAmount;
}
}
所以再一次,这个问题并不是关于如何围绕它,因为我已经这样做了,但是为什么它首先要做到这一点。我从未在任何其他语言中体验过这一点。