Codepen: https://codepen.io/anon/pen/BqGvrr?editors=1000
Я пытаюсь написать программу для расчета платы за стоимость здания. Пользователь вводит число, а затем вычисляет плату за строителя на основе этого числа.
Первые 5000 зданий составляют 8%.
Еще 3% для остатка до 80 000 включительно,
ИЛИ 2,5%, если остаток составляет более 80 000.
У меня есть первые 5000, которые касаются простого утверждения if. Я знаю, что должен закончить другие 2 условия с помощью else if, но я не могу подумать о том, как "настроить" только определенную часть введенного пользователем номера? aka, если они вводят 70 000, как я нацелился на первые 5000 на 8%, тогда применяю 3% комиссионных к оставшимся 65 000... и т.д. Спасибо!
PS извините за раздражающее приглашение окна в codepen lol.
<!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\ 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\ 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 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\ fee will be $' +
architectFee +
'.';
// Display output message with building cost and architect fee
document.write(outputMessage);
}
part04();
Кажется, что есть три условия, с которыми вы имеете дело: менее 5000, более 5000, но менее 80 000 и более 80 000. В двух случаях, которые еще не написаны, вы можете сохранить оставшуюся стоимость и рассчитать дополнительные затраты.
Таким образом, вы можете оставить свои оставшиеся предметы следующим образом:
else if (costOfBuilding <= 80,000) {
var remainingCost = costOfBuilding - 5000;
architectFee = 5000 * .08 + remainingCost * .03;
}
else {
var remainingCost = costOfBuilding - 5000;
architectFee = 5000 * .08 + remainingCost * .025;
}
OR 2.5% if the remainder is more than 80,000.
Просто чтобы убедиться, это звучит так, как будто общая сумма составляет 85 001, общая сумма будет меньше, чем если бы общая сумма составила 84 999?outputMessage = 'For a building that costs $'...
part, это обычное явление, поэтому вы можете переместить его после того, какif...else...
условия уменьшат ваш код.