gpt4 book ai didi

javascript - 如何计算不同数量的费用百分比变化的费用? Vanilla javascript

转载 作者:行者123 更新时间:2023-11-30 09:19:04 24 4
gpt4 key购买 nike

代码笔:https://codepen.io/anon/pen/BqGvrr?editors=1000

我正在尝试编写一个程序来计算建筑成本的费用。用户输入一个数字,然后根据该数字计算建筑费。

大厦前5000为8%。

剩余 80,000 及以下的另 3%,

如果余数超过 80,000,则为 2.5%。

我用一个简单的 if 语句处理了前 5000 个。我知道我应该用 else if 语句完成其他 2 个条件,但我想不出如何仅“定位”用户输入号码的特定部分?也就是说,如果他们输入 70,000 个,我如何针对前 5000 个收取 8%,然后对剩余的 65,000 个收取 3% 的费用...等等。谢谢!

附言抱歉,codepen 中的烦人窗口提示大声笑。

<!DOCTYPE html>
<html>
<body>

<script language="JavaScript" type="text/javascript">
function part04() {

// Define all variables
var costOfBuilding;
var builderFee;
var outputMessage;

// Obtain building cost from user
costOfBuilding = prompt('What is the cost of the building?');

// Convert user string to a number
costOfBuilding = Number(costOfBuilding);

// Calculate builder fee
if (costOfBuilding <= 5000) {
builderFee = costOfBuilding * .08;
outputMessage = 'For a building that costs $'
+ costOfBuilding
+ ' the architect\'s fee will be $'
+ architectFee
+ '.';
}

// Display output message with building cost and builder fee
document.write(outputMessage);
}
</script>

<pre>
<script language="JavaScript" type="text/javascript">
part04();
</script>
</pre>

</body>
</html>

更新。下面的答案引导我回答,只需进行一些调整以正确适合公式。谢谢大家!

if (costOfBuilding <= 5000) {
builderFee = costOfBuilding * .08;
} else if (costOfBuilding > 5000 && costOfBuilding <= 85000) {
remainingCost = costOfBuilding - 5000;
builderFee = (5000 * .08) + remainingCost * .03;
} else if (costOfBuilding > 85000) {
remainingCost = costOfBuilding - 5000;
builderFee = (5000 * .08) + remainingCost * .025;
}

outputMessage = 'For a building that costs $'
+ costOfBuilding
+ ' the architect\'s fee will be $'
+ builderFee
+ '.';

最佳答案

如下更新您的计算并删除 if 条件。:

architectFee = (Math.min(costOfBuilding, 5000) * 0.08) + (Math.max(costOfBuilding - 5000, 0) * (costOfBuilding > 80000 ? 0.025 : 0.03));

function part04() {

// Define all variables
var costOfBuilding;
var architectFee;
var outputMessage;

// Obtain building cost from user
costOfBuilding = prompt('What is the cost of the building?');

// Convert user string to a number
costOfBuilding = Number(costOfBuilding);

// Calculate architect's fee

//architectFee = (Math.min(costOfBuilding, 5000) * 0.08) + (Math.max(costOfBuilding - 5000, 0) * 0.03) + (Math.max(costOfBuilding - 80000, 0) * 0.025);
architectFee = (Math.min(costOfBuilding, 5000) * 0.08) + (Math.max(costOfBuilding - 5000, 0) * (costOfBuilding > 80000 ? 0.025 : 0.03));

outputMessage = 'For a building that costs $' +
costOfBuilding +
' the architect\'s fee will be $' +
architectFee +
'.';


// Display output message with building cost and architect fee
document.write(outputMessage);
}

part04();

关于javascript - 如何计算不同数量的费用百分比变化的费用? Vanilla javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52981027/

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