0

Screenshot of my Output

On the image the highlighted 0.03 should be 0.04 but showing 0.03 and coin needed should be 10 but showing 9

My Code:

#include <stdio.h>

int main(){

    double coins[6] = {0.01,0.05,0.10,0.25,1,2};
    double ans[15];
    double V = 5.64;
    int j=0,i=5,Tcoin = 0;
    while(V>coins[0])
    {
        if(coins[i]<=V)
        {
            j = V/coins[i];
            //printf("%.2lf - %.2lf = %.2lf\n",V,j*coins[i],V-(j*coins[i]));//This is for testing purpose
            V = V-(j*coins[i]);
            Tcoin += j;
        }
        i--;
    }
    printf("Number of coin needed is: %d\n",Tcoin);

    return 0;
}
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Déjà vu Nov 26 '17 at 14:53
  • Because of exactly this kind of problem, one should never use floating-point arithmetic for money. For change-making and simple accounting, use integer cents for everything. It can be necessary to use integers scaled to some fraction of a cent for calculations involving compound interest, but don't worry about that until you get there. – zwol Nov 26 '17 at 14:55
  • 1
    As there is only 2 digits after decimal points (in case of currency)..convert your money and corresponding denomination in integer multiplying with `100` and then proceed with the same algorithm. What you need at the end is the number of denominations.. – user2736738 Nov 26 '17 at 14:57
  • Add a #define double int below , multiply `V` and `coins` items by 100 and your program works – Déjà vu Nov 26 '17 at 15:20

0 Answers0