0

所以一切正常,除了我的 if 语句 >=largeOrder 它不会打折。对于作为承包商的员工也不会。我们必须在那里做出决定,给每个人最好的折扣,如果员工是承包商,他会得到承包商折扣。但是,如果声明是完美的并且工作正常,则常规承包商。所有输出都是正确的。所以我用我的嵌套 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>
4

3 回答 3

4

我认为你需要使用if-else-if

修改 if 块

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
}
于 2013-10-26T22:20:23.113 回答
2

问题是您if每次都在使用,而不是else if,这会使您的最后一个 if/else 语句运行discount = smallOrderDiscount;,除非客户是承包商。这只是一个逻辑错误。

于 2013-10-26T22:20:38.460 回答
1

解决此问题的最佳方法是添加关键字

debugger;

就在那些 if 语句之前。然后按 F12(在浏览器中)并重新加载页面,您应该会发现,当您下次运行代码时,您会在断点处停止,然后您可以使用 F12 工具单步执行并查看发生了什么。

于 2013-10-26T22:11:19.030 回答