gpt4 book ai didi

javascript - 如何使循环购买最大金额?

转载 作者:行者123 更新时间:2023-11-30 09:41:55 26 4
gpt4 key购买 nike

我正在尝试让我的代码购买最大数量的手机和配件。一部手机售价 99.99,配件售价 9.99。我的银行帐户上有 1000。我如何让我的代码购买最大数量?我的代码目前购买了 9 部手机和 9 部配件。它应该购买 9 部手机和 10 部配件,而不是 9 部。

const ACCESSORY = 9.99;
const PHONE = 99.99;

var balance = 1000;
var total = 0;

var phones_total = 0;
var accessories_total = 0;

while (((total + PHONE) || (total + ACCESSORY)) < balance) {
total = total + PHONE;
phones_total = phones_total + 1;
if ((total + ACCESSORY) < balance) {
total = total + ACCESSORY;
accessories_total = accessories_total + 1;
}
}

console.log("total = " + total);
console.log("phones = " + phones_total);
console.log("accessories = " + accessories_total);

最佳答案

这一行是错误的:

while (((total + PHONE) || (total + ACCESSORY)) < balance) {

这不会测试任何一个总和是否小于 balance . (total + PHONE) || (total + ACCESSORY) 的值总是 total + PHONE除非那是 0 , 然后是 total + ACCESSORY .自 total + PHONE永远不会 0 ,这实际上等同于:

while ((total + PHONE) < balance) {

而且它从不测试是否只有一个配件有可用余额。做这个测试的正确方法是:

while ((total + PHONE) < balance || (total + ACCESSORY) < balance) {

您还应该使用 <=而不是 < , 以便准确使用您所有的钱。

但是在循环中,你仍然添加 PHONEtotal ,即使只剩下足够的余额来购买配件。您需要先检查一下。

const ACCESSORY = 9.99;
const PHONE = 99.99;

var balance = 1000;
var total = 0;

var phones_total = 0;
var accessories_total = 0;

while ((total + PHONE) <= balance || (total + ACCESSORY) <= balance) {
if ((total + PHONE) <= balance) {
total = total + PHONE;
phones_total = phones_total + 1;
}
if ((total + ACCESSORY) <= balance) {
total = total + ACCESSORY;
accessories_total = accessories_total + 1;
}
}

console.log(phones_total, accessories_total);

一个更简单的方法是使用算术而不是循环。将余额除以手机 + 配件的成本,找出您可以负担得起的对数。然后找出您可以用剩下的东西购买多少配件。

const ACCESSORY = 9.99;
const PHONE = 99.99;

var balance = 1000;

var phones_total = Math.floor(balance/(PHONE + ACCESSORY));
var remainder = balance - phones_total*(PHONE+ACCESSORY)
var accessories_total = phones_total + Math.floor(remainder/ACCESSORY);

console.log(phones_total, accessories_total);

关于javascript - 如何使循环购买最大金额?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40726499/

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