No worries, I like helping people when I can. To be honest I feel kind of silly that I didn't see some of these things earlier.
Now, I'm not sure what your current divide function looks like, since I'm not sure if it's been modified since you posted it here. I'm just going to assume it still looks like the following:
1 2 3 4
|
int DollarsCents::divide(int const num)
{
return (dollars + cents)/num;
}
|
Which does yield some strange results.
Let's assume I have 5 dollars and 10 cents.
If I divide that amount of money by 2, the result should be $2.55 (2 dollars and 55 cents).
Here's what your divide function actually returns:
1.) (dollars + cents) = 5 + 10 = 15
2.) 15/2 = 7.5
3.) And, because it's an integer that's getting returned, it would return 8.
Which, as we know, is not correct.
By the way, based on your original post, it looks like your instructor wants this function (and the multiply function) to also return a DollarsCents object, not an integer, which makes sense.
I would probably do something like this:
1 2 3 4 5 6 7 8 9 10 11 12
|
DollarsCents DollarsCents::divide(const int num) {
int totalCents = (dollars*100) + cents;
totalCents /= num;
DollarsCents temporary(0, totalCents);
temporary.simplify();
return temporary;
}
|
First, we declare a variable named "totalCents". We then convert dollars into cents by multiplying the dollars by 100. We add the converted dollars and the cents to totalCents. Now, we can work with the currency more easily than if we didn't convert everything to one format.
Then, we perform the actual division.
Next, we create a new DollarsCents object called "temporary", and pass zero dollars and totalCents as arguments to its constructor.
Then, we call temporary's method "simplify" to effectively convert its cents into dollars and cents.
Finally, we return the temporary DollarsCents object.
You can also use the above function as a "template" function for your multiply() function, which probably isn't correct either. They're basically the same, only that in the case of multiply(), you're not dividing, but instead, multiplying.