C++ floating point accuracy in while loops

前端 未结 4 442
暖寄归人
暖寄归人 2021-01-23 04:10

I am trying to count the amount of dollar and coin denominations in a grand total by using a series of while loops. When I get down to the coins however, I am off by a penny. Wh

4条回答
  •  孤城傲影
    2021-01-23 04:54

    Here's the fixed code, I used TJD's advice and instead of using .01 i used .0099 instead. For my problem that seems to work, thanks guys!

        #include 
    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;
       float p = .0099, n = .0499, d = .099, q = .2499;   
       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 >= q)
       {
          quarters = quarters +1;
          amount = amount - q;
    
       }
       while (amount >= d)
       {
          dimes = dimes +1;
          amount = amount - d;
    
       }
       while (amount >= n)
       {
          nickels = nickels +1;
          amount = amount - n;
    
       }
       while (amount >= p)
       {
          pennies = pennies +1;
          amount = amount - p;
    
       }
    
    
       cout<

提交回复
热议问题