1.1 ask
user to enter rate per mile 1.2 read in rate per mile 1.3 ask user to enter mileage 1.4 read in mileage 2.1 calculate cost = rate x mileage 3.1 print the mileage
|
It is important to note that the reason for doing this is not to make extra work for ourselves - it's so that we can use the design to code the program. 2. Code the Program The program needs to use three numbers - the number of
miles, the rate per mile and the cost of the journey. We
now need to decide i) what to call these numbers, an
identifier and, ii) what type of numbers they are. Here's
our suggestion, listed in a table: |
identifier | type |
rate | REAL |
miles | INTEGER |
cost | REAL |
Remember that whole numbers are INTEGERs. Numbers which might have a decimal part are called REAL numbers. So, now for the code... |
PROGRAM bus_journey;
{to calculate journey cost} VAR {by A Programmer} rate : REAL; miles : INTEGER; cost : REAL; BEGIN WRITELN('enter the rate per mile '); READLN(rate); WRITELN('enter the number of miles '); READLN(miles); cost := rate * miles; WRITELN('number of miles = ', miles); WRITELN('rate per mile = $', rate); WRITELN('cost of journey = $', cost) END. |
Notice how closely the code corresponds to our design.
Again, you'll see that the results are not what you perhaps expected.
WRITELN('rate
per mile = $', rate :5:2);
WRITELN('number of miles = ', miles); We're going to make one or two more changes now...
WRITE('enter the rate per mile '); (notice we're using WRITE instead of WRITELN)
WRITE('enter the number of miles ');
3. Test the Program Once you have the program working, you should test it to make sure it works properly. For example, we might draw up a table like the one below and check out various possibilities. What happens if you enter 6.5 for the number of miles? It is, after all, supposed to be a whole number.
|
rate | miles | expected answer | result or comment |
2 | 50 | ||
0.25 | 100 | ||
0 | 100 | ||
3 | 6.5 | ||
3 | mmm |