Assume that type Money, a structured type with two int fields, dollars and cents
ID: 3632712 • Letter: A
Question
Assume that type Money, a structured type with two int fields, dollars and cents, has been declared. Also assume the availability of a function named normalize that receives a Money argument and returns a "normalized" Money value (i.e. one that is equivalent to the argument but where the cents values is between 0 and 99).
Now write the definition of a function named addMoney that receives two Money arguments and returns their sum, in normalized form. So if the equivalent of $1.85 and $2.19 is passed the function would return the equivalent of $4.04.
Now Assume that type Money, a structured type with two int fields, dollars and cents, has been declared. Write the definition of a function named normalize that receives a Money argument and returns a Money value. What it returns is the "normalized" equivalent of the argument, that is, a value that is equivalent but where cents is a number between 0 and 99 inclusive. So if a Money value of 5 dollars and 325 cents was passed, a Money value of 8 dollars and 25 cents would be returned.
Explanation / Answer
Pseudocode:
function addMoney( Money money1, Money money2 )
sum -> A Money object with dollars and cents each set to 0
set sum's dollars to ( money1's dollars + money2's dollars )
set sum's cents to ( money1's cents + money2's cents )
return normalize( sum )
function normalize( Money money )
cents -> money's cents
while ( cents - 100 ) is greater than or equal to zero...
set cents to ( cents - 100 )
increment money's dollars by one
set money's cents to the current value of variable cents
return money