Question
Assume you are given a variable, payRate of type Money (a structured type with two int fields, dollars and cents). Write the necessary code to increase the effective value of payRate by $1.50. To do this you need to add 50 to cents and 1 to dollars but you ALSO must make sure that cents does not end up over 99: if it does, you need to "carry a one" to dollars. For example, if payRate were $12.80 then a naive addition of $1.50 yields 13 (dollars) and 130 (cents). This would have to be changed to 14 (dollars) and 30 (cents).
Solution
Money payRateIncrease;
payRateIncrease.dollars=1;
payRateIncrease.cents=50;
payRate.dollars += payRateIncrease.dollars + (payRate.cents + payRateIncrease.cents)/100;
payRate.cents = (payRate.cents + payRateIncrease.cents) % 100;
Answers for C++ Course using "Starting out with C++ : from control structures through objects" by Tony Gaddis. 7/8th ed. I used the Pearson myprogramminglab to complete the homework. Here are my solutions/answers for the exercises/labs so please use the test bank as a GUIDE if you're stuck. Let me know if you find a better solution to a problem or any of the programming challenges. Thanks in advance for your support! Send in missing programming challenges to cplusplus.answers@gmail.com
here's my solution:
ReplyDeletepayRate.dollars += 1;
payRate.cents += 50;
if (payRate.cents > 99)
{
payRate.dollars += 1;
payRate.cents = payRate.cents - 100;
}
Nice. Two different ways. Did it pass the test?
ReplyDeleteHere is mine (since we add $1.50. We suppose that the maximum value of cents can be added is 50 cents)
ReplyDeleteif(payRate.cents < 50)
{
payRate.dollars += 1;
payRate.cents += 50;
}
else
{
payRate.dollars += 2;
payRate.cents -= 50;
}