使用取模运算符的剩余变化量 (JavaScript)

Leftover change amount using modulus operator (JavaScript)

我正在做一项作业,要求我将任意数量的便士兑换成适当数量的 25 美分、10 美分、5 美分和剩余的便士。

当我 运行 程序时,它使用 Math.floor() 将总量转换为每个相应的硬币。此脚本在头部 运行ning,根据作业要求:

<!DOCTYPE html>
<html lang="en">


<head>
<meta charset="utf-8" />
<title>Make Change</title>
<meta name="generator" content="Geany 1.29" />

<script>
function convertChange(numberOfQuarters, numberOfDimes, numberOfNickels, numberOfPennies) {

number=parseFloat(document.getElementById("penniesBox").value);
numberOfQuarters = Math.floor(number/25);
numberOfDimes = Math.floor(number/10);
numberOfNickels = Math.floor(number/5);
numberOfPennies = Math.floor(number/1);
    document.getElementById("outputDiv").innerHTML=
        'Quarters: ' + numberOfQuarters + "<br>" + 
        'Dimes: ' + numberOfDimes + "<br>" + 
        'Nickels: ' + numberOfNickels + "<br>" + 
        'Pennies:' + numberOfPennies;

}

</script>
</head>

<body>
<h2>Make Change</h2>
<p>This page will tell you the minimum amount of pennies, nickels, dimes and quarters you need to match the number of pennies entered.</p>
<p>Enter a number of pennies:
<input type="text" id="penniesBox" size=12 value="">
</p>
    <input type="button" value="Show me the money!"
    onclick="convertChange();">


<hr>
<div id="outputDiv"></div>




</body>

</html>

我将如何使用取模运算符来让剩余的便士数量显示在适当的找零金额旁边?

使用模数获取您将在以后的计算中使用的剩余金额 (Math.floor...),用剩余金额覆盖每笔钱。此外,由于您没有在 onclick 中将变量传递给您的函数(请注意它只是 convertChange()),您应该使用 var ....

在函数中声明您的变量

在此处查看更新的代码:

function convertChange() {
    var money = parseFloat(document.getElementById("penniesBox").value); 
    var numberOfQuarters = Math.floor(money/25);
    money = money%25;
    var numberOfDimes = Math.floor(money/10);
    money = money%25;
    var numberOfNickels = Math.floor(money/5);
    money = money%5;
    var numberOfPennies = money;
        document.getElementById("outputDiv").innerHTML=
            'Quarters: ' + numberOfQuarters + "<br>" + 
            'Dimes: ' + numberOfDimes + "<br>" + 
            'Nickels: ' + numberOfNickels + "<br>" + 
            'Pennies:' + numberOfPennies;
}
<h2>Make Change</h2>
<p>This page will tell you the minimum amount of pennies, nickels, dimes and quarters you need to match the number of pennies entered.</p>
<p>Enter a number of pennies:
<input type="text" id="penniesBox" size=12 value="">
</p>
    <input type="button" value="Show me the money!"
    onclick="convertChange();">


<hr>
<div id="outputDiv"></div>