我正在做一個小程式來測驗C語言中的浮點:程式本身非常簡單,我只是想根據用戶的輸入,回傳他的數字有多少Dollar(s), Quarter(s)... etc。
//------------------------------> 第一部分。所有必要的變數 <-----------------------------
int main (void)
{
//Getting the user Input
float number = get_float("Number: ")。
//Checking if is a positive number[/span]。
if (number < 0)
{
printf("A positive number, Please: ");
}
//Declaring my Constant/Temporary variables.。
float coinValues[] = {1.00, 0. 25, 0.10, 0.5, 0.01};
char *coinNames[] = {"$(s): ", "quarter(s): ", "Dime(s): ", "鎳幣(s): ", "Penny(ies): "}。
int i = 0;
int tmp = 0;
//-----------------------------------> 第二部分。代碼本身 <-----------------------------------
//Checking/Printing the necessary coins.。
while (number > 0)
{
//Until the loop stops, check if the number can be divided by the CoinValue.
if (number >= coinValues[i])
{
//Print the current Coin Name from the divided value.
printf("%s", coinNames[i]) 。
//Check if the Current Number still contains Coin Values inside of it, if True counts one in your "Coin Score".
while (number >= coinValues[i])
{
number -= coinValues[i];
tmp 。
}
//Print the Current "Coin Score", then resets TMP.
printf("%i
", tmp)。)
tmp = 0;
}
else; }
{
//Updating the Coin value {
i ;
}
}
}
只要我使用Integers,我的程式運行得非常好,但是當我將這段代碼轉換為Floats時,值(Dime(s), Nickel(s), and Penny(ies))開始在Int變數tmp回傳非預期
對于像2. 6,將是2美元,2硬幣,和1硬幣,但有時,程式沒有使用硬幣,而是完全跳過它們,用鎳進行操作,然而,令我困擾的是,程式總是回傳AWL= ,沒有任何值,然后程式永遠凍結了。
考慮到這一點,我唯一的想法是我 "遭受 "了浮點不精確,我不知道如何解決它,所以誰能幫幫我?
Ps.程式需要始終從每個硬幣中回傳最大值,然后再向前傳遞
。uj5u.com熱心網友回復:
浮點運算是為了接近實數運算而設計的。IEEE 754-2008說:"浮點算術是對實數算術的系統性近似......" 因此,在二進制浮點運算中,沒有辦法 "鎖定 "十進制數字。它旨在用于你想要近似值的地方,比如物理建模。這甚至包括一些金融應用,如期權評估。盡管在某些情況下,浮點運算可以用于精確計算,但這需要特別小心,通常只有在特殊情況下才會采用。
因此,對于您提出的如何鎖定小數位的問題,二進制浮點運算沒有很好的辦法。試圖這樣做通常只會產生與整數算術相同的效果,但效率更低,代碼也更難。因此,使用整數算術,并根據所需的最小貨幣單位(如1分錢)來調整金額。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/319977.html
標籤:
