It's an efficient approach and you're on the right track! The problem is that it's calculating the total number of each type of coin required, but not accounting for the previous calculations. [EDIT: oops, wrong!]
Simply put, after accounting for the total number of quarters, the code needs to subtract the value of the quarters from the total before calculating dimes, and so on.
[EDIT: corrected answer]
Rafael perceived that there was an error in my analysis in his comment, although maybe not seeing the real problem. I was in error in my original analysis.
After reviewing it, I discovered that the true problem lies in the following code:
int p = (change - (25 * q) + (10 * d) + (5 * n)) / 1;
This line of code isn't calculating the correct number of pennies! It's supposed to subtract the value of quarters, dimes and nickels to see how many pennies remain. The problem is that there should be a set of parentheses around those three sections. Since there isn't, it subtracts the value of quarters, but then ADDS the value of dimes and nickels! OOPS! That's the real problem and my bad for not seeing it.
While it's a creative technique, and would be correct without that error, it shows that creative isn't necessarily good. A good rule of thumb in programming is to keep it simple. "Creative" often leads to the introduction of errors, just like this! It would have been both simpler and more obvious to just keep a running total in change to avoid complication. The simpler code would have been to do this:
int q = change / 25;
change -= 25 * q
int d = change / 10;
change -= 10 * d
int n = change / 5;
int p -= change ;
coins = q + d + n + p;
The logic is this: calculate the number of a given type of coin, then subtract the value of those coins from the total. Repeat as needed. This also would require about 10 operations vs. 15 or 16 in the original code.
The point is this. Simpler is almost always better!
If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)
d
andn
compared top
. – DinoCoderSaurus Apr 27 '20 at 22:01