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.
but % does not only work with whole numbers?
– cand
Indeed. I will correct. Times I do not work with C.
– Rafael Barros