所以一切正常,除了带有> = largeOrder的if语句,它不会放在折扣中。对于作为承包商的员工也不会。我们必须在那里做出决定,给予每个人最大的折扣,如果员工是承包商,他会得到承包商的折扣。然而,定期承包商if声明是完美的,并且工作正常。所有输出都是正确的。所以我用我的嵌套if语句来猜测它...
//assumptions
var employeeDiscount = .1;
var largeOrder = 800;
var largeOrderDiscount = .05;
var smallOrderDiscount = 0;
var contractorDiscount = .2;
var salesTax = .08;
var seniorTax = 0;
var seniorAge = 90;
var tax, typeOfCustomer, orderAmount, employeeContractor;
var discount, discountAmount, subtotal, finalPrice, taxTotal;
//input
age = prompt("How old is the customer", "");
age = parseInt(age);
orderAmount = prompt("How much is the order", "");
orderAmount = parseInt(orderAmount);
typeOfCustomer = prompt("What type of customer is it, regular, employee, or contractor", "");
//calculations
if (age >= seniorAge) {
tax = seniorTax;
} else {
tax = salesTax;
}
if (typeOfCustomer == "regular") {
if (orderAmount >= largeOrder) {
discount = largeOrderDiscount;
} else {
discount = smallOrderDiscount;
}
}
if (typeOfCustomer == "employee") {
employeeContractor = prompt("is the employee a contractor?", "");
if (employeeContractor == "yes") {
discount = contractorDiscount;
} else {
discount = employeeDiscount;
}
}
if (typeOfCustomer == "contractor") {
discount = contractorDiscount;
} else {
discount = smallOrderDiscount;
}
taxTotal = orderAmount * tax;
discountAmount = orderAmount * discount;
subtotal = orderAmount - discountAmount;
finalPrice = subtotal + taxTotal;
//output
document.write("Order amount: $" + orderAmount);
document.write("<br>Discount amount: $" + discountAmount);
document.write("<br>Subtotal: $" + subtotal);
document.write("<br>Taxes: $" + taxTotal);
document.write("<br>Final Price is: $" + finalPrice);
// -->
</script>
答案 0 :(得分:4)
我认为您需要使用if-else-if
修改if block
if (typeOfCustomer == "regular") {
if (orderAmount >= largeOrder) {
discount = largeOrderDiscount;
} else {
discount = smallOrderDiscount;
}
} else if (typeOfCustomer == "employee") {
employeeContractor = prompt("is the employee a contractor?", "");
if (employeeContractor == "yes") {
discount = contractorDiscount;
} else {
discount = employeeDiscount;
}
} else if (typeOfCustomer == "contractor") {
discount = contractorDiscount;
} else {
discount = smallOrderDiscount;
}
根据我的理解,代码中的问题是最后的if-block。
if (typeOfCustomer == "contractor") {
discount = contractorDiscount;
} else {
discount = smallOrderDiscount; // <== Here previous discount will be overridden if typeOfCustomer is not contractor
}
答案 1 :(得分:2)
问题是您每次都使用if
而不是else if
,这会使您的最后一个if / else语句运行discount = smallOrderDiscount;
,除非客户是承包商。这只是一个逻辑错误。
答案 2 :(得分:1)
解决此问题的最佳方法是添加关键字
debugger;
就在那些if语句之前。然后按F12(在浏览器中)并重新加载页面,您应该在下次运行在断点处停止的代码时找到,然后您可以使用F12工具逐步查看正在发生的事情。