C语言中十进制数的计算错误

时间:2014-02-15 07:13:30

标签: c floating-point cs50

我正在尝试计算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); } 

}

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

2 个答案:

答案 0 :(得分:1)

你正在达到你的epsilon限制。由于您使用浮动,因此FLT_EPSILON的表示受限制;如果你使用的是double,你会看到DBL_EPSILON的分辨率提高了。 (这些值来自&lt; float.h&gt;)

#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 */

因此,如果您使用的值大致为10000,那么您的值变化最小的是10000 * FLT_EPSILON附近的值,大约为0.012。如果您希望以更好的精度表示,请使用双精度。

答案 1 :(得分:0)

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

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

相关问题