Write a program that reads in a distance in miles, then calculates and displays the corresponding taxi fare. Each taxi ride incurs a fixed standard charge of £5 and a variable fare, which depends on the distance required. The price per mile is calculated according to the rules below:
• First 2 miles (inclusive): £3.80 per mile
• Over 2 miles and up to 10 miles (inclusive): £2.00 per mile.
• Over 10 miles: £1.50 per mile.
For example, the total taxi fare for a 12.50-mile ride is £32.35 (i.e., (2*3.8) + (8*2.0) + (2.5*1.5) of variable fare and £5 of fixed standard charge)
Write a C++ program for this problem. Your solution must include (at least) one void function, named calculateVariableFare, which is called when the distance is valid. It calculates the variable part of the taxi fare (i.e., the part of the cost that depends directly and solely on the mileage) and sets a global variable, named variableFare, to that value.
In addition, I just allowed to use void, if, while or do while functions. I am really stuck and I don't know how to start it. I really appreciate your help.
With any problem like this, the first thing to do is to try and break it down into steps. Then you can tackle each step individually. So with this problem, your steps might be:
- Read in a distance in miles
- Check that the distance is valid
- Use that distance to calculate the variable part of the price
- Add the variable part of the price to the fixed part to get the total price
- Output that total price
The first and last steps are simple I/O - presumably you've covered that in class?
The third step is where the maths comes in, and you might need to think in a bit more detail how to do that. It looks as though your teacher has given you quite a lot of detail there, especially in the example. They've also given you some quite detailed advice on things you'll do in your code.
But if you're still confused about this bit then the same advice applies - think about it logically, and break it down into steps.
Think first about how you would work it out on paper. Think about the steps you have to take to do that calculation. Once you're clear on that, it will be easier to write the code to do the same calculation.