I need you to help me with this issue in C

Asked

Viewed 70 times

-3

I have a question about my code. I think my logic is correct, however, the change in $1.00R notes is not working properly. Any suggestions?

#include <stdio.h>
    int main()
    {

    int valor_produto = 0, valor_pagamento = 0, troco = 0;
    scanf("%d", &valor_produto);
    scanf("%d", &valor_pagamento);
    troco = valor_pagamento - valor_produto;
    if (valor_pagamento  > valor_produto ){
        printf("100: %d\n", troco / 100);
        printf("50: %d\n", troco % 100 / 50);
        printf("20: %d\n", troco % 50 / 20 );
        printf("10: %d\n", troco % 20 / 10);
        printf("5: %d\n", troco % 10 / 5);
        printf("2: %d\n", troco % 5 / 2);
        printf("1: %d\n", troco / 2 );
    }
    else printf("O valor pago é insuficiente, faltam %d R$",troco * -1);

    return 1;



    }
  • Because by your logic you always take first the biggest notes you can form the desired value.

  • But be correct?

  • No. Instead of always starting from the initial change value for each calculation keep in return only the rest of the division with the value of the previous note.

  • So it would be good? printf("100: %d n", change / 100); printf("50: %d n", change % 100 / 50); printf("20: %d n", change % 100 % 50 / 20 ); printf("10: %d n", change % 100 50 %20 / 10); printf("5: %d n", change % 100 % 50 % 50 % 20 % 10 / 5); printf("2: %d n", change % 100 % 50 % 20 % 10 % 5 / 2); printf("1: %d n", change % 100 % 50 % 20 % 10 % 5 % 2 / 1 ); }

  • It may be. Note that it doesn’t make much sense to divide by 1 on the last printf. You may not have studied vectors but its use will certainly greatly simplify your program.

1 answer

0

The idea of this question is to remember that, if Voce has, for example, 155 real, Voce knows that:

  • The amount of hundreds will be equal to 155/100, remembering that we are considering the entire division. That is, we have a hundred bill, and the rest is 55. So we would have to work with 55 real.

In short, the main idea to solve the problem is to always know how to update the change value, IE:

#include <stdio.h>

int main() {

int valor_produto = 0, valor_pagamento = 0, troco = 0;
scanf("%d", &valor_produto);
scanf("%d", &valor_pagamento);
troco = valor_pagamento - valor_produto;
if (valor_pagamento  > valor_produto ){
    printf("100: %d\n", troco / 100);
    troco = troco%100;
    printf("50: %d\n", troco / 50) ;
    troco= troco %50;
    printf("20: %d\n", troco / 20) ;
    troco = troco %20;
    printf("10: %d\n", troco / 10) ;
    troco = troco %10;
    printf("5: %d\n", troco / 5) ;
    troco = troco%5;
    printf("2: %d\n", troco / 2);
    printf("1: %d\n", troco%2   );
}
else printf("O valor pago é insuficiente, faltam %d R$",troco * -1);

return 1;
}

The variable change will always receive the rest of the last division.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.