1

I have C code which simulates contact-less checkout.

Enter value of your bill: 50
Insert money for payment: 50 20 5 0.10 0
You have inserted: 75.1
To return: 25.1

I have to achieve this:

Collect your payback: 20 5 0.10

I can use only use this nominal values:

float allowedMoney[13] = {100, 50, 20, 10, 5, 2, 1, 0.50, 0.20, 0.10, 0.05, 0.02 , 0.01};

Any idea how to do it? Thank you very much

main() function

int main() {
    float bill = getBill();

    float payment = insertPayment();

    if(!payment) return 1;

    printf("You have inserted: %g\n", payment);


    if(payment < bill) {
        printf("Not enough money!\n");
        return 1;
    }

    float toReturn = payment - bill;
    printf("To return: %g\n", toReturn);

    if(toReturn > 0) {
        int payback = getPayback(toReturn);
        print ... (HELP)    
    }
    return 1;
}

EDIT: I have variable with value for example: 25.1

I have to output in one line this: 20 5 0.10 Thats the "20 Dollars + 5 Dollars + 10 Cents" I have to transfer number 25.1 to format of dollars and cents like this: 20 5 0.10

20 5 0.10

20 + 5 + 0.10 but without +

Erik Balog
  • 33
  • 1
  • 5

2 Answers2

3

In general, don't use use float types to represent currency. They are prone to rounding errors, they can't exactly represent large numbers, and it is probably not worth the effort just to be able to get something after the decimal point. Instead, use an integer type to represent the number of pennies, or cents, and print values using something like this:

printf("$%d.%02d", amount/100, amount%100);

If you want to represent very large numbers, you can always use long long instead of int. A plain 32-bit integer can represent $21,474,836.47, whereas an IEEE float32 cannot represent $167,772.17.

Tim Randall
  • 4,040
  • 1
  • 17
  • 39
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/184041/discussion-on-answer-by-tim-randall-print-float-as-money-payback-in-c). –  Nov 21 '18 at 15:42
1

Is your question, "how do I keep prompting for payment until it's greater than or equal to the bill?"

If so, wrap (approximately) the below code in a loop (while) control

So:

float payment = insertPayment();

if(!payment) return 1;

printf("You have inserted: %g\n", payment);


if(payment < bill) {
    printf("Not enough money!\n");
    return 1;
}

becomes something like:

while(payment < bill)
{
    printf("Not enough money!\n");
    float payment = insertPayment();

    printf("You have inserted: %g\n", payment);

 }
static_cast
  • 1,174
  • 1
  • 15
  • 21