2016-07-25 8 views
-1

私はCS50の貪欲問題を解決しようとしていますが、それは正しく計算されません。私は常に0.00の代わりに0.01を残しています。最後はペニーを除いてすべてが円滑に実行されます。私は何をすべきか分からない。あなたが入力したら、9.99を試してみてください。ペニーなしの数字ではうまく動作します。計算が正しく行われていません

ありがとうございます!

int main() 
{ 
    // declaring variables for coins 

    float const qtr = 0.25; 
    float const dimes = 0.10; 
    float const nick = 0.05; 
    float const penny = 0.01; 

    //declaring variables for coin counters 

    int qtr_count = 0; 
    int dimes_count = 0; 
    int nick_count = 0; 
    int penny_count = 0; 

    //declaring variables for total debt and rest of debt 

    float total; 
    float rest; 

    //loop for testing is the number entered valid 

    do 
    { 
     printf("Enter the ammount of money he owns:\n"); 
     scanf("%f", &total); 
    } 
    while (total < 0.00) ; 

    rest = total; 

    //Loop for calculating coins 

    while (rest >= qtr) 
    { 
     qtr_count++; 
     rest -= 0.25; 
    } 

    while (rest >= dimes) 
    { 
     dimes_count++; 
     rest -= 0.10; 
    } 

    while (rest >= nick) 
    { 
     nick_count++; 
     rest -= 0.05; 
    } 

    while (rest >= penny) 
    { 
     penny_count++; 
     rest -= 0.01; 
    } 

    printf("You need go give: \n %i quarters, \n %i dimes, \n %i nick, \n %i pennies \n", qtr_count, dimes_count, nick_count, penny_count); 

    return 0; 

} 
+2

このような金銭的計算は、純粋にintで行うことができます。必要なものに100を掛ければ、おそらく少しだけ速く動作します。 – StoryTeller

答えて

0

浮動小数点演算は必ずしも正確ではない可能性があります。整数だけを使うことをお勧めします。人にセントで額を入力させる(または100を掛ける)。そうすれば、浮動小数点演算で問題が発生することはなく、より効率的になります。

関連する問題