gpt4 book ai didi

javascript - 从便士更改计算器 - js

转载 作者:行者123 更新时间:2023-11-30 20:28:03 25 4
gpt4 key购买 nike

我正在开发一个小应用程序来提高我的 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,它将返回除法整数结果的数组以及 xy 之间的欧氏除法的余数。为此,我将像您一样使用 % 模数运算符和 Math.floor() 函数:

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

    我使用的是简写 arrow function表达式来声明它。


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

    使用我们之前的divide 函数,这很容易做到,你只需要写这行:

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

    通过 destructuring divide(x, 200) 返回的数组,我们将除法结果分配给 obj 的属性 twoPounds 并将余数分配给划分为 x

    同样的结果会遇到:

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

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

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


  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(),我创建了一个包含 namelabel 的对象和每枚硬币的 值(value)

    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 }
    ];
  • 然后在函数中我使用 .map方法遍历 coins 数组的每个元素。 span 格式中硬币数量的计算发生在同一行。 .map 返回的数组然后被转换为带有 .join 的字符串添加到元素 #result 中。

    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>

关于javascript - 从便士更改计算器 - js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50666232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com