Click here to Skip to main content
15,113,855 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
I'm finishing up a school assignment, and I've got this code

void dispense_change(int denomination, int price_in_cents)
{
   int denom_value=denomination*100;
   int change = denom_value-price_in_cents;
   int loonies = change / 100;
   int ql = change % 100;
   int halfloonies = ql / 50;
   int qh = ql % 50;
   int quarters = qh / 25;
   int qq = qh % 25;
   int dimes = qq / 10;
   int qd = qq % 10;
   int nickels = qd / 5;
   int pennies = qd % 5;
   printf("%d loonies + %d half-loonies + %d quarters + %d dimes + %d nickels + %d pennies\n",loonies, halfloonies, quarters, dimes, nickels, pennies);
}


Works so far, but I need to have the results be in terms of letters ie If there are two loonies, I need it to display LL for instance, and if there are six quarters I need it to print QQQQQQ.

Is there a way to accomplish this?

What I have tried:

I tried editing the last sentence, but it churns out quite a few errors.
Posted
Updated 6-Oct-21 5:59am

1 solution

Quote:
Is there a way to accomplish this?
Yes, use the count of the items to decide how many of each letter you need to display. So rather than trying to print the complete line in one go, break it down into its separate parts. You can then create a function that prints the letters, something like:
C++
void letters(char letter, int count, char* suffix)
{
    while (count-- > 0)
    {
        printf("%c", letter);
    }
    printf(" %s ", suffix);

You then call it like:
C++
letters('L', 3, "loonies");

which will prodiuce:
LLL loonies 

ready to be followed by the next set ...
   
Comments
Member 15373566 6-Oct-21 11:15am
   
Thank you! Quick question, this part "letters('L', 3, "loonies");" is to be pasted within the the formulas itself right
Richard MacCutchan 6-Oct-21 11:22am
   
No, it is a separate function; it goes before dispense_change and is called from within it. But you may want to spend some time actually thinking of maybe other ways to solve this. Your teacher may not appreciate you just copying my code.
Member 15370412 6-Oct-21 11:26am
   
Got it, thanks
KarstenK 6-Oct-21 14:14pm
   
For the sake of performance I would use sprintf and strcat to create a result string at first. Use a big enough buffer for that.
Richard MacCutchan 7-Oct-21 3:27am
   
Exactly my thought but possibly more complicated for a beginner.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900