C ++ - Gleitkommagenauigkeit in while-Schleifen

Ich versuche, mithilfe einer Reihe von while-Schleifen die Stückelung von Dollars und Münzen in einer Gesamtsumme zu berechnen. Wenn ich jedoch zu den Münzen komme, bin ich um einen Cent daneben. Wenn ich beispielsweise 99,95 eingebe, erhalte ich die Ausgabe 3 Viertel, 1 Cent, 1 Nickel und 4 Cent. Ich habe das Problem auf ein Problem mit der Gleitkommagenauigkeit eingegrenzt. Alle Lösungen, die ich recherchiert habe, waren jedoch in meiner Situation nicht anwendbar. Irgendwelche Hinweise?

#include <iostream>
using namespace std;

int main()

{
   float amount;
   cout<<"enter amount" << endl;
   cin>>amount;
   int pennies=0, nickels=0, dimes=0, quarters=0, ones=0, fives=0, 
tens=0, 
twenties=0, fifties=0, hundreds=0;

   while (amount >= 100) 
   {
      hundreds = hundreds +1;
      amount = amount - 100;

   }
   while (amount >= 50)
   {
      fifties = fifties +1;
      amount = amount - 50;

   }
   while (amount >= 20)
   {
      twenties = twenties +1;
      amount = amount - 20;

   }
   while (amount >= 10)
   {
      tens = tens +1;
      amount = amount - 10;

   }
   while (amount >= 5)
   {
      fives = fives +1;
      amount = amount - 5;

   }
   while (amount >= 1)
   {
      ones = ones +1;
      amount = amount - 1;

   }
   while (amount >= .25)
   {
      quarters = quarters +1;
      amount = amount - .25;

   }
   while (amount >= .10)
   {
      dimes = dimes +1;
      amount = amount - .10;

   }
   while (amount >= .05)
   {
      nickels = nickels +1;
      amount = amount - .05;

   }
   while (amount >= .01)
   {
      pennies = pennies +1;
      amount = amount - .01;

   }


   cout<<endl<<"pennies:"<< pennies;
   cout<<endl<<"nickels:"<<nickels;
   cout<<endl<<"dimes:"<<dimes;
   cout<<endl<<"quarters:"<<quarters;
   cout<<endl<<"ones:"<<ones;
   cout<<endl<<"fives:"<<fives;
   cout<<endl<<"tens:"<<tens;
   cout<<endl<<"twenties:"<<twenties;
   cout<<endl<<"fifties:"<<fifties;
   cout<<endl<<"hundreds:"<<hundreds<<endl;







return 0;
}

Antworten auf die Frage(4)

Ihre Antwort auf die Frage