The problem is calculating the total cost to be paid to the taxi driver with the following rules:
- for the first hundred meters, the rental rate is 100 / meter.
- for the next hundred meters to the first 500 meters, the rental rate is 50 / meter.
- for 500 meters to the end, the rental rate is 10 / meter.
the unit of distance entered is kilo meters.
(It’s the easy part to change the distance so don’t bother.)
Since this is a problem from the pop quiz and I didn’t study at all, I just came out with this solution
function counter(distance) {
distance = distance * 1000;
meter = 0;
totalCost = 0;
while (meter <= distance) {
if (meter <= 100) {
totalCost = 100;
}
if (meter > 100 && meter <= 500) {
totalCost = totalCost + 50;
}
if (meter > 500) {
totalCost = totalCost + 10;
}
meter = meter + 1;
}
return totalCost;
}
Which is so stupid because there are so many repetitions. Can you guys show me the right way to solve this problem?
Source: Ask Javascript Questions