user3251700 - 6 months ago 30

C Question

I'm trying to calculate the decimal amount in

`float`

`#include <stdio.h>`

#include <cs50.h>

float MCounting = 0.00;

int MAmountCoin = 0;

float MAmountUsed = 0.00;

int MCoinCount = 0;

float MRemainAmount = 0;

int MCoinOut = 0;

int MTotCoinOut = 0;

int main(void)

{

float Amount;

float MRemainAmount;

do

{

printf("Specify the amount you want in change: ");

Amount = GetFloat();

MRemainAmount = Amount;

}

while (Amount < 0 );

if (MRemainAmount > 0 || MRemainAmount < .05 )

printf ("\n\n ***** Calculatin for 0.01 *****\n");

{

printf ("MRemainAmount Before calculation: %.2f\n",MRemainAmount);

MCoinOut = MRemainAmount / .01;

printf ("MCoinOut = %i...MTotCoinOut = %i\n",MCoinOut,MTotCoinOut);

MRemainAmount = MRemainAmount - (MCoinOut * .01);

printf ("MRemainAmount = %.2f\n",MRemainAmount);

MTotCoinOut = MCoinOut + MTotCoinOut;

printf ("MTotCoinOut = %i\n",MTotCoinOut);

}

{ printf("Total Coin Out%i\n",MTotCoinOut); }

}

What's going wrong and how can I fix it?

Answer

You are hitting your epsilon limit. Since you are using floats you are limited in representation by FLT_EPSILON; if you were using a double, you would see improved resolution of DBL_EPSILON. (These values are from <float.h>)

```
#define DBL_EPSILON 2.2204460492503131e-016 /* smallest such that 1.0+DBL_EPSILON != 1.0 */
#define FLT_EPSILON 1.192092896e-07F /* smallest such that 1.0+FLT_EPSILON != 1.0 */
```

Thus if you are using a value like 10000, roughly, you're smallest change in value is something in the vicinity of 10000 * FLT_EPSILON, which would be about .012. If you want to represent with better precision, use doubles.