Вы находитесь на странице: 1из 2

Fundamentals of Programming  Homework Semester 1

HOMEWORK #5 (SELECTION IN C++)

5. Implement in C++ the following PDL program (developed for Homework #4) that reads in a
distance in miles, then calculates and displays the shipping cost.

global shippingDistance, variableShippingCost

produceShippingCost
local totalShippingCost
local const fixedShipmentCost = 50

output( "Enter the distance in miles: ")


input( shippingDistance)
if ( shippingDistance ≥ 0) then
//calculate part of the cost that varies with the distance
call calculateVariableCost
//add fixed charge
set totalShippingCost to (variableShippingCost + fixedShipmentCost)
//display cost
output( “The total shipment cost is: £”, totalShippingCost)
else //when distance is negative
//display error message
output( “ERROR: Cannot calculate cost: invalid distance!”)
endif

proc calculateVariableCost //calculate part of the cost that varies with the distance
if ( shippingDistance ≤ 100) then //distance ≤ 100
//£5 per mile
set variableShippingCost to (5 * shippingDistance)
else //distance > 100
if ( shippingDistance ≤ 500) then //distance > 100 and distance ≤ 500
//£5 for each of first 100 miles, £4 for remaining miles
set variableShippingCost to ( (5 * 100)
+ (4 * (shippingDistance - 100)) )
else //distance > 500
//£5 for first 100 miles, £4 for next 400 miles, £3 for remaining distance
set variableShippingCost to ( (5 * 100)
+ (4 * 400)
+ (3 * (shippingDistance - 500)) )
endif
endif
endproc

Format the program's outputs so that it shows the cost in the usual currency format, e.g.,

Enter the distance in miles:: 520.5


The total shipment cost is: £2211.50

25471259.doc, 25/11/09 Module 4374, Homework1


Fundamentals of Programming  Homework Semester 1

For this exercise, you should:


• Use C++ facilities for implementing selection (if .. else) sequences & functions
(NO need for repetition).
• Keep the structure of the PDL algorithm given in your C++ program (same
procedures, same order, same logic).
• Use the global and local variables/constants declared.
• Use the identifiers given in PDL for the variables & functions in your C++
program.
• Put comments (between the two // up to the end of the line or between
/* and */) to give information about your program, the functions &
variables it used so as to make your solution easier to understand.
• Format your program's outputs as specified (see solution to Homework
#3).
• Test your program with the various distances (e.g., try, at least -10, 0, 50, 100,
200, 500, 520 and also 10.5).

You do not have to check the validity of the type of the input (i.e. you can assume that the user
will only enter a number for the distance).

Look at section 3.4 in the C++ notes & refer to tutorial sheet # 4 to find out how to format the
output for currency (£ sign and numbers representing pounds and pence).

25471259.doc, 25/11/09 Module 4374, Homework2