我試圖計算float
中的十進制數,但如果輸入爲「0.01」,則不計算。但是,它會計算輸入是否爲「0.02」但計算錯誤。這裏是代碼:C語言中十進制數的錯誤計算
#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); }
}
怎麼回事,我該如何解決它?
在我的電腦上,用'MRemainAmount * 100'替換MRemainAmount/.01'解決了這個問題。 – Levans
浮點數不是表示貨幣的好方法,因爲它們確實是一個定點值。用美分和整數來考慮可能更好。 (您仍然可以要求用戶獲得浮點金額並立即將其轉換爲分。) –
我的問題是,如果我將總金額轉換爲美分,並且輸入是「5.4」,那麼我如何處理結果「504」的方式是首先將.25c硬幣,然後是.10c,.05c硬幣和最後的.01c硬幣。 – user3251700