2016-04-08 23 views
0

我想寫一個賬單更換器的代碼,其中插入的金額被轉換回硬幣爲用戶。問題是當我輸入111.111時,我一直保持小數點數爲50c,如222.222。我的20C和10C未使用。請幫助試圖寫一個賬單更換器/硬幣自動售貨亭的代碼

#include <stdio.h> 

int main() 

{ 
    double sum50c=0, sum20c=0, sum10c=0, remainder, remainder2, remainder3, end=0; 
    double amount; 

    do 
    { 

    printf("Please enter an amount(dollars):"); 
    scanf("%lf", &amount); 

    amount=amount*100; 

    if(amount<0){ 
     printf("Invalid Input\n"); 
     printf("Re-enter your amount:"); 
     scanf("%lf", &amount); 
    } 

    if(amount>=50){ 
     remainder=amount/50; 
     sum50c=remainder; 

    }else 
    if(remainder!=0){ 
     remainder2=remainder/20; 
     sum20c=remainder2; 

    }else  
    if(remainder2!=0){ 
     remainder3=remainder3/10; 
     sum10c=remainder3; 

    } 

    if(sum50c>200||sum20c>200||sum10c>200){ 
     end++; 
    }else{ 
     end=0; 
    } 

    } 
     while(end<=0); 

    printf("The amount of 50cents=%lf, 20cents=%lf, 10cents=%lf", sum50c, sum20c, sum10c); 


} 
+6

,則不應使用實數。使用整數,因爲硬幣是分散分佈的,並且沒有5.55美分硬幣。以美分工作(1美分是原子的,不能有任何小於這個數值的東西)。 –

+0

另外,'something/x'給你的商數,而不是餘數。按照建議更改爲整數,然後在'%'(模)運算符上進行讀取。 – Lundin

回答

0

要強制amount有整數值的分裂後,你應該四捨五入值:

if(amount>=50) 
{ 
     remainder=round(amount/50); 
     sum50c=remainder; 
} 
1

基本上有在你的代碼的兩個錯誤:

  • 不要在這裏對浮點數進行操作。硬幣的數量將是一個離散數字,應該表示爲int或者甚至可以是unsigned int。爲了簡單起見,該數量本身可以作爲浮點數讀入,但爲了避免舍入錯誤,還應將其轉換爲整數分數。
  • 你必須找到硬幣的組合:30c是1%倍; 20c + 1 × 10c。這意味着你不能使用else if鏈,它只會考慮一種類型的硬幣。首先處理所有類型的硬幣,先硬幣,然後減少仍需處理的數量。請注意,使用10c作爲最小硬幣時,您可能無法完全更改所有金額。

這裏是你沒有如外循環並沒有怪end業務:

#include <stdlib.h> 
#include <stdio.h> 

int main() 
{ 
    int num50c = 0, 
     num20c = 0, 
     num10c = 0; 
    int amount;    // amount in cents 
    double iamount;   // input amount in dollars 

    printf("Please enter an amount: "); 
    scanf("%lf", &iamount); 

    amount = iamount * 100 + 0.5; 

    if (amount < 0) { 
     printf("Invalid Input\n"); 
     exit(1); 
    } 

    num50c = amount/50; 
    amount %= 50; 

    num20c = amount/20; 
    amount %= 20; 

    num10c = amount/10; 
    amount %= 10; 

    printf("%d x 50c = %d\n", num50c, num50c * 50); 
    printf("%d x 20c = %d\n", num20c, num20c * 20); 
    printf("%d x 10c = %d\n", num10c, num10c * 10); 
    printf("Remainder: %dc\n", amount); 

    return 0; 
}