0
因此,我是新的,並試圖編寫一個程序來獲取輸入的金額$ XX.XX,然後顯示最少金額的金額,以使金額。我做了一個可行的程序,但是在做一些計算時經常是一分錢,例如13.49,我不知道爲什麼。c輸入金額的最小金額
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int StayOn = 1;
while (StayOn == 1)
{
int x = 0;
float MoneyStart = 0, RemainingMoney = 0;
char cName[6][8] = {"Toonie", "Loonie", "Quarter", "Dime", "Nickel", "Penny"};
float cValue[6] = {2.00, 1.00, 0.25, 0.10, 0.05, 0.01};
int cCount[6] = {0, 0, 0, 0, 0, 0};
printf("Please Enter Amount: $");
scanf("%f", &MoneyStart);
getchar();
RemainingMoney = MoneyStart;
for (x = 0; x < 6; x++)
{
cCount[x] = (RemainingMoney/cValue[x]);
RemainingMoney = fmod(RemainingMoney, cValue[x]);
printf("%8s - %3i = $%.2f\n", cName[x], cCount[x], (cValue[x]*cCount[x]));
}
}
}
您可能需要閱讀[「?是浮點運算破」(http://stackoverflow.com/questions/588004/is-floating-point-math-broken) 。如果你改變使用'double',它可能會變得更好,但是一般來說,使用浮點類型來獲取金錢遲早會導致舍入錯誤,並且每次計算都會變得複雜。 –