代码之家  ›  专栏  ›  技术社区  ›  Quantum_Compass

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

  •  -1
  • Quantum_Compass  · 技术社区  · 7 年前

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

    当我运行该程序时,它使用 Math.floor() . 此脚本正在头部运行,这是分配所需的:

    <!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>
    

    我该如何使用模数运算符来获得剩余的便士数,以便在适当的变化量旁边显示?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Blue    7 年前

    使用“模数”获取将在以后的计算中使用的剩余量( 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>