0

It is correct for every input except "4.2". The output should be 18, but my code is giving it to be 22 and I have absolutely no idea why this is happening.

#include<cs50.h>
#include<stdio.h>

int main (void)
{  
   float n = -1;
   printf("O hai! ");
   while (n < 0)
   { 
     printf("How much change is owed?\n");  
     n = GetFloat();   
   };

    n = n * 100;
    int count = 0;
    int A[] = {25, 10, 5, 1};
    int i;

    for (i = 0; i < 4; i++)
    {  
        while (n >= A[i])
       {
           n = n - A[i];
           count++;
       }
    }


    printf("%d\n", count);
}

My CHECK50 screenshot is here: CHECK50

The only conclusion I could deduce is that the universe is trying to tell me something (the number 42). Thank you for reading this question.

1
1

It is happening because you are not rounding off your value of n before further calculations. This is required because of the imprecision of float. Similar to the fact that, (1/10) is not stored exactly as 0.1 in computer.

You might use round() function for this purpose. It is a part of math.h

n = 100*n; m = round(n);

NOTE - You might want to convert n to int after rounding off.

2
  • Thank you very much for solving my problem :) I believe you were the one to solve my last problem too. Thanks a lot, I really appreciate it! :D – samidha Jun 26 '16 at 11:49
  • you are welcome! – abhishek Jun 26 '16 at 13:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .