95.8k views
1 vote
Assume you are given three variables, revenue, expenses, and profit, all of type Money (a structured type with two int fields, dollars and cents). Assign to profit the result of subtracting expenses from revenue. Let's make the happy assumption that revenue exceeds expenses. However you still may find that the cents part of expenses exceeds that of revenue. If that is the case you will have to "borrow" 1 from revenue dollars (i.e. subtract 1) and "give" it to revenue's cents (i.e. add 100!) in order to carry out the subtraction properly.

User Cloudhead
by
4.2k points

1 Answer

1 vote

Answer:

if(revenue.cents - expenses.cents < 0){

profit.dollars = revenue.dollars - expenses.dollars - 1;

profit.cents = 1 - revenue.cents - expenses.cents;

}

else{

profit.dollars = revenue.dollars - expenses.dollars;

profit.cents = revenue.cents - expenses.cents;

}

Step-by-step explanation:

We know that profit is given as: revenue - expenses from the question.

From the given expression above;

if(revenue.cents - expenses.cents < 0)

then profit.dollar will be revenue.dollars - expenses.dollars - 1; the 1 is to be carry over to the cent part. And the profit.cent will be 1 - revenue.cents - expenses.cents;

else the profit.dollars and the profit.cent is computed directly without needing to carry over:

profit.dollars = revenue.dollars - expenses.dollars;

profit.cents = revenue.cents - expenses.cents;

User Krzaq
by
4.4k points