从便士更改计算器 - js

Change calculator from pennies - js

我正在开发一个小应用程序来提高我的 js 技能。它旨在允许用户输入一定数量的便士,并从这里计算出正确的最小零钱数额。

目前我输入的便士是按正确的面额计算的(1p、2p、5p、10p、20p、50p、1 英镑、2 英镑),但是我不确定如何让它显示补足总硬币数所需的最少零钱?

以下是我到目前为止的代码,任何帮助将不胜感激,因为我真的很想学习如何做这件事:

function calculate() {
  var list = []
  var x = document.getElementById("pennies").value;

  resultTwoPounds = x / 200;
  resultTwoPounds * 2;
  list.push(Math.floor(resultTwoPounds));

  resultPounds = x / 100;
  list.push(Math.floor(resultPounds));

  remaining = x % 100;
  remainPennyFifty = Math.floor(remaining / 50);
  list.push(remainPennyFifty);

  remaining = x % 100;
  remainPennyTwenty = Math.floor(remaining / 20);
  list.push(remainPennyTwenty);

  remaining = x % 100;
  remainPennyTen = Math.floor(remaining / 10);
  list.push(remainPennyTen);

  remaining = x % 10;
  list.push(Math.floor(remaining / 5));

  remaining = x % 10;
  list.push(Math.floor(remaining / 2));

  remaining = x % 10;
  list.push(Math.floor(remaining));

  if (x > 0) {
    resultLine = "You have <strong>" + x + " pennies</strong>, breakdown as follows: <br><br><strong>£2</strong> *" + list[0] + "<br><br><strong>" + "£1</strong> *" + list[1] + "<br><br><strong>50p</strong>" + " *" + list[2] + "<br><br><strong>20p</strong>" + " *" + list[3] + "<br><br><strong>10p</strong>" + " *" + list[4] + "<br><br><strong>5p</strong>" + " *" + list[5] + "<br><br><strong>2p</strong>" + " *" + list[6] + "<br><br><strong>1p</strong>" + " *" + list[7]
  } else {
    resultLine = "Please enter an amount"
  }

  document.getElementById('result').innerHTML = resultLine;

  $("#submit").submit(function(e) {
    e.preventDefault();
  });
}
#pennies {
  width: 6em;
  vertical-align: middle;
}

#submit {
  text-align: center;
}

.mainCalc {
  text-align: center;
  align-content: center;
}

.headings {
  text-align: center;
  color: white;
}

body {
  margin-top: 200px;
  background-color: lightblue;
}

#printResult {
  text-align: center;
  padding-top: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="headings">
  <h1>pennyCalc
    <h1>
</div>

<!-- Start of form -->
<form onsubmit="return false">
  <div class="mainCalc">
    <br>
    <strong>p:</strong>
    <input type="number" placeholder=" Amount" step="1" min="0" id="pennies">
    <br>
    <button type="buttom" id="submit" onclick="calculate()">Calculate!</button>
    <br>
  </div>
</form>
<div id="printResult"><span id="result"></span></div>

一个提案

我已经制作了一个你的计算器版本,如果可以的话,让我向你展示它是如何工作的。

功能相同,但我组织它的方式不同。你不需要使用 jQuery(因为你没有在这个问题上加上 jQuery 标签)。

  1. 让我们创建一个函数divide,它将return除法整数结果的数组和x和[=之间的欧氏除法的余数28=]。为此,我将像您一样使用 % 取模运算符和 Math.floor() 函数:

    const divide = (x, y) => { return [ Math.floor(x/y), x % y ] };
    

    我正在使用 shorthand arrow function 表达式来声明它。


  2. 然后我们将编写实际函数calculate():声明obj,将包含值的对象和x,货币计数。在每一步中,我们都会减少 x 的值并将新属性附加到对象 obj.

    使用我们之前的 divide 函数,这很容易做到,您只需编写以下行:

    [ obj['twoPounds'], x ] = divide(x, 200);
    

    通过destructuringdivide(x, 200)编辑的数组return,我们将除法结果分配给obj的属性 twoPounds并将除法的剩余部分分配给 x.

    同样的结果会遇到:

    let result = division(x, 200);
    obj['twoPounds'] = result[0];
    x = result[1]
    

    但是你只调用一次,而不是调用函数两次,而且代码更简洁。

    为每种硬币类型调用divide后,x将具有0的值,obj将填充每种硬币类型的硬币数量。


  3. 最后,我们可以使用带有反引号 (`) 和 ${} 语法的 template literals 来格式化我们的响应。这样我们就可以在字符串中嵌入 JavaScript 变量,也可以在编辑器中编写 HTML 标记时跳转行。

    例如:

    `You have ${obj.twoPounds} coins of £2`
    

    写法一样:

    'You have' + obj.twoPounds + 'coins of £2'
    

JavaScript 代码和预览

const divide = (x, y) => { return [Math.floor(x / y), x % y] };

const calculate = function() {
  let obj = {};
  let x = document.querySelector('#pennies').value;

  [ obj['twoPounds'], x ] = divide(x, 200);
  [ obj['onePound'], x ] = divide(x, 100);
  [ obj['fiftyPence'], x ] = divide(x, 50);
  [ obj['twentyPence'], x ] = divide(x, 20);
  [ obj['tenPence'], x ] = divide(x, 10);
  [ obj['fivePence'], x ] = divide(x, 5);
  [ obj['twoPence'], x ] = divide(x, 2);
  [ obj['onePence'], x ] = divide(x, 1);

  document.querySelector('#result').innerHTML = `
        <div>
          <span>You have: </span>
          <span><strong>${obj.twoPounds}</strong> x £2, </span>
          <span><strong>${obj.onePound}</strong> x £1, </span>
          <span><strong>${obj.fiftyPence}</strong> x 50p, </span>
          <span><strong>${obj.twentyPence}</strong> x 20p, </span>
          <span><strong>${obj.tenPence}</strong> x 10p, </span>
          <span><strong>${obj.fivePence}</strong> x 5p, </span>
          <span><strong>${obj.twoPence}</strong> x 2p, </span>
          <span><strong>${obj.onePence}</strong> x 1p, </span>
        </div>
      `;

  return false;
}

预览:

const divide = (x, y) => { return [ Math.floor(x / y), x % y ] };

const calculate = function() {
  let obj = {};
  let x = document.querySelector('#pennies').value;

  [ obj['twoPounds'], x ] = divide(x, 200);
  [ obj['onePound'], x ] = divide(x, 100);
  [ obj['fiftyPence'], x ] = divide(x, 50);
  [ obj['twentyPence'], x ] = divide(x, 20);
  [ obj['tenPence'], x ] = divide(x, 10);
  [ obj['fivePence'], x ] = divide(x, 5);
  [ obj['twoPence'], x ] = divide(x, 2);
  [ obj['onePence'], x ] = divide(x, 1);

  document.querySelector('#result').innerHTML = `
    <div>
      <span>You have: </span>
      <span><strong>${obj.twoPounds}</strong> x £2, </span>
      <span><strong>${obj.onePound}</strong> x £1, </span>
      <span><strong>${obj.fiftyPence}</strong> x 50p, </span>
      <span><strong>${obj.twentyPence}</strong> x 20p, </span>
      <span><strong>${obj.tenPence}</strong> x 10p, </span>
      <span><strong>${obj.fivePence}</strong> x 5p, </span>
      <span><strong>${obj.twoPence}</strong> x 2p, </span>
      <span><strong>${obj.onePence}</strong> x 1p, </span>
    </div>
  `;

  return false;
}
#pennies {
  width: 6em;
  vertical-align: middle;
}

#submit {
  width: 10em;
  text-align: center;
}

.mainCalc {
  text-align: center;
  align-content: center;
}

.headings {
  text-align: center;
  color: white;
}

body {
  margin-top: 200px;
  background-color: lightblue;
}

#printResult {
  text-align: center;
  padding-top: 40px;
}
<div class="headings">
  <h1>Penny Calculator</h1>
</div>

<div class="mainCalc">
  <input type="number" placeholder=" Amount" value="593" step="1" min="0" id="pennies">
  <button type="buttom" id="submit" onclick="calculate()">Calculate!</button>
</div>
<div id="printResult"><span id="result"></span></div>


更短的版本

我继续重构我自己的版本,实际功能本身很短确实,享受!

  • 不必多次调用函数 divide(),我创建了一个包含 namelabelvalue 的对象每个硬币一分钱。

    let coins = [
        { name: 'twoPounds', label: '£2', value: 200 },
        { name: 'onePound', label: '£1', value: 100 },
        { name: 'fiftyPence', label: '50p', value: 50 },
        { name: 'twentyPence', label: '£2', value: 20 },
        { name: 'tenPence', label: '£2', value: 10 },
        { name: 'fivePence', label: '£2', value: 5 },
        { name: 'twoPence', label: '£2', value: 2 },
        { name: 'onePence', label: '£2', value: 1 }
    ];
    
  • 然后在函数中我使用在元素#result中添加的.map method to go through each element of the coins array. The calculation of the number of coins in the formatting of the spans happens on the same line. The array returned by .map is then converted into a string with .join

    document.querySelector('#result').innerHTML = `
     <div>
      <span>You have: </span>
      ${ coins.map( coin => `<span>${([x, x] = divide(x, coin.value))[0]} x ${coin.label}</span>` ).join(', ') }
     </div>
    `
    

这行代码基本上完成了所有工作:

${ coins.map( coin => `<span>${([x, x] = divide(x, coin.value))[0]} x ${coin.label}</span>` ).join(', ') }


这是最终代码(与预览版结果相同):

const divide = (x, y) => { return [ Math.floor(x / y), x % y ] };
let coins = [
    { name: 'twoPounds', label: '£2', value: 200 },
    { name: 'onePound', label: '£1', value: 100 },
    { name: 'fiftyPence', label: '50p', value: 50 },
    { name: 'twentyPence', label: '£2', value: 20 },
    { name: 'tenPence', label: '£2', value: 10 },
    { name: 'fivePence', label: '£2', value: 5 },
    { name: 'twoPence', label: '£2', value: 2 },
    { name: 'onePence', label: '£2', value: 1 }
];

const calculate = function() {
  
  
  let x = document.querySelector('#pennies').value;
  
  document.querySelector('#result').innerHTML = `
    <div>
      <span>You have: </span>
      ${ coins.map( coin => `<span>${([x, x] = divide(x, coin.value))[0]} x ${coin.label}</span>` ).join(', ') }
    </div>
  `

  return false;
}
#pennies {
  width: 6em;
  vertical-align: middle;
}

#submit {
  width: 10em;
  text-align: center;
}

.mainCalc {
  text-align: center;
  align-content: center;
}

.headings {
  text-align: center;
  color: white;
}

body {
  margin-top: 200px;
  background-color: lightblue;
}

#printResult {
  text-align: center;
  padding-top: 40px;
}
<div class="headings">
  <h1>Penny Calculator</h1>
</div>

<div class="mainCalc">
  <input type="number" placeholder=" Amount" value="593" step="1" min="0" id="pennies">
  <button type="buttom" id="submit" onclick="calculate()">Calculate!</button>
</div>
<div id="printResult"><span id="result"></span></div>