0

I need to solve the following problem:

Write a program that asks the user to enter a U.S. dollar amount and the shows how to pay that amount using the smallest number of $20, $10, $5 and $1 bills.

I don't know how to extract the change of the first dividing bill to 20 amount and after to continue with 10, 5 and 1.

I had written the following code but is not solving my quest:

#include <stdio.h>

int main(void)
{
    int value1, value2, value3, value4, bill, change;
    printf("Put the bill value: ");
    scanf_s("%d", &bill);

    value1 = bill/ 20;
    rest = bill- (bill/ 20);
    value2 = bill /10 //  Tried with this but not  working:(bill-(bill/20))/10;
    value3 = bill/ 5;
    value4 = bill/ 1;

    printf("The amount is: %d$. \n", bill);

    printf("change=%d", change);
    /*printf(" $20 Bill:  \n", value1);
    printf("$10 Bill:  \n", value2);
    printf("$5 Bill: \n", value3);
    printf("$1 Bill:  \n", value4);*/

    return 0; 
}

It would help me a lot if you could explain to me how to solve correctly this problem.

static_cast
  • 1,174
  • 1
  • 15
  • 21
  • Where is `rest` declared? Please include a [mcve] – Govind Parmar Feb 22 '19 at 16:45
  • 1
    `rest = bill- (bill/ 20);` doesn't do what you think it does. Say your change is 70 dollars. 70/20 = 3. Now you want to find the remainder. So 70-(3*20) is how you would find that remainder. – Dustin Nieffenegger Feb 22 '19 at 16:45
  • [Just say "No" to using `scanf_s()`](https://stackoverflow.com/questions/50724726/why-didnt-gcc-implement-s-functions). Pay particular attention to the documents linked in the comments. – Andrew Henle Feb 22 '19 at 17:02

2 Answers2

0

You have problem with calculating the rest value. So please use this solution:

rest  = bill;
value1 = rest / 20;
rest = rest % 20;
value2 = rest /10 ;
rest = rest % 10;
value3 = rest / 5;
rest = rest % 5;
value4 = rest / 1;
Loc Tran
  • 1,170
  • 7
  • 15
0

Something like that

#include <stdio.h>

int main()
{
  int v;

  if ((scanf("%d", &v) == 1) && (v > 0)) {
    int bills[] = { 20, 10, 5, 1 };
    size_t i;

    for (i = 0; i != sizeof(bills) / sizeof(int); ++i) {
      int n = v/bills[i];

      if (n != 0) {
        printf("%d*%d$ ", n, bills[i]);
        v %= bills[i];
      }
    }

    putchar('\n');
  }
}

Compilation and execution :

pi@raspberrypi:/tmp $ gcc -Wextra r.c
pi@raspberrypi:/tmp $ ./a.out
123
6*20$ 3*1$ 
pi@raspberrypi:/tmp $ ./a.out
1234
61*20$ 1*10$ 4*1$ 
bruno
  • 32,421
  • 7
  • 25
  • 37