Problem with C code

Asked

Viewed 192 times

1

I have a problem to solve in C which is as follows:

Read a double precision number and calculate the minimum amount of 100, 50, 20, 10, 2 and 1 real, 50 cents, 25 cents, 10 cents, 5 cents and 1 cent notes.

I tried the two codes below, but they’re not working.

#include<stdio.h>
int main() {
double entrada, m[12] = {100, 50, 20, 10, 5, 2, 1, 0.50, 0.25, 0.10, 0.05, 0.01}, aux = 0;
int i, n[12];
scanf("%lf",&entrada);
for (i = 0; i < 12; i++){
    n[i] = (entrada - aux)/m[i];
    aux = aux + n[i]*m[i];
}
double res = 0;
for (i = 0; i < 12; i++)
    res = res + n[i]*m[i];
if (res != entrada) n[11]++;
for (i = 0; i < 12; i++){
    if (i == 0) printf("NOTAS:\n");
    else if (i == 6) printf("MOEDAS:\n");
    printf("%d ",n[i]);
    if (i < 6) printf("nota(s) ");
    else printf("moeda(s) ");
    printf("de R$ %.2lf\n",n[i],m[i]);
}
return 0;
}

and that

#include<stdio.h>
int main() {
double entrada, mo[12] = {100, 50, 20, 10, 5, 2, 1, 0.50, 0.25, 0.10, 0.05, 0.01};
int intermediario, i, n[12], m[12] = {10000, 5000, 2000, 1000, 500, 200, 100, 50, 25, 10, 5, 1};
scanf("%lf",&entrada);
intermediario = (int) 100*entrada;
for (i = 0; i < 12; i++){
    n[i] = intermediario/m[i];
    intermediario = intermediario%m[i];
}
for (i = 0; i < 12; i++){
    if (i == 0) printf("NOTAS:\n");
    else if (i == 6) printf("MOEDAS:\n");
    printf("%d ",n[i]);
    if (i < 6) printf("nota(s)");
    else printf("moeda(s)");
    printf(" de %.2lf\n",mo[i]);
}
return 0;
}

They should work, but in some cases they’re giving a few cents of difference and I have no idea how to solve.

1 answer

1


The complete, revised and tested solution:

int main(void) {

    float dinheiro;
    scanf("%f",&dinheiro);        // input do usuário
    dinheiro = dinheiro * 100;    // multiplico por 100 para não trabalhar com float
    int entrada = (int)dinheiro;  // transformo em inteiro

    int valor[12]={10000, 5000, 2000, 1000, 500, 200, 100, 50, 25, 10, 5, 1};
    int resultado[12];

    for (int i=0; i<12; i++) {
        resultado[i] = entrada/valor[i];                             // calcula
        printf("%.2f:\t%d\n", (double)valor[i]/100.0, resultado[i]); // exibe
        entrada = entrada - (resultado[i] * valor[i]);               // atualiza
    }

}
  • but % does not only work with whole numbers?

  • Indeed. I will correct. Times I do not work with C.

Browser other questions tagged

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