The following range-checking code works but is somewhat inefficient. Explain why and show how to revise it to be more efficient.if (saleAmount >= 1000)commissionRate = 0.08;else if (saleAmount >= 500)commissionRate = 0.06;else if (saleAmount <= 499)commissionRate = 0.05;
What will be an ideal response?
This version of the code works, but it is somewhat inefficient because it executes as follows:
When saleAmount is less than $1000 but at least $500, the first Boolean test is false, but the second one is true, so commissionRate is assigned .06 and the if structure ends. The only saleAmount values that reach the third Boolean test are under $500, so the next Boolean test, if (saleAmount <= 499), is always true. When an expression is always true, there is no need to evaluate it. In other words, if saleAmount is not at least $1000 and is also not at least $500, it must by default be less than or equal to $499.
The improved code is:
if (saleAmount >= 1000)
commissionRate = 0.08;
else if (saleAmount >= 500)
commissionRate = 0.06;
else commissionRate = 0.05;
You might also like to view...
Use a light touch on the keyboard to prevent backache.
Answer the following statement true (T) or false (F)
Computer hardware sold today is so reliable it rarely needs repairs or replacement.
Answer the following statement true (T) or false (F)