我试图计算float中的十进制数,但如果输入为“0.01”,则不计算。但是,它会计算输入是否为“0.02”但计算错误。这里是代码:C语言中十进制数的错误计算
#include
#include
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); }
}
怎么回事,我该如何解决它?
+0
在我的电脑上,用'MRemainAmount * 100'替换MRemainAmount/.01'解决了这个问题。 –
+1
浮点数不是表示货币的好方法,因为它们确实是一个定点值。用美分和整数来考虑可能更好。 (您仍然可以要求用户获得浮点金额并立即将其转换为分。) –
+0
我的问题是,如果我将总金额转换为美分,并且输入是“5.4”,那么我如何处理结果“504”的方式是首先将.25c硬币,然后是.10c,.05c硬币和最后的.01c硬币。 –