0

我正在尝试计算小数,float但如果输入为“0.01”,它将无法计算。但是,如果输入为“0.02”但计算错误,它将计算。这是代码:

#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); } 

}

出了什么问题,我该如何解决?

4

2 回答 2

1

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.

于 2014-02-15T07:37:01.897 回答
0

这是由于计算机内存中浮点数的不精确表示。

阅读http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

于 2014-02-15T07:16:59.810 回答