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

イプシロンの限界に達しています。フロートを使用しているため、FLT_EPSILON による表現が制限されています。double を使用していた場合、DBL_EPSILON の解像度が向上します。(これらの値は <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 */

したがって、10000 のような値を使用している場合、おおよそ、値の最小の変化は 10000 * FLT_EPSILON 付近で、約 .012 になります。より高い精度で表現したい場合は、double を使用してください。

于 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 に答える