Platinum Partner

Accuracy Issues With Floating Point Numbers In C++


#include 
#include 
#include 

int main(void) {
  double total = 1, price;
  int cnt = 0;
  std::cout << std::setprecision(20);
  for(price = 0.1; total >= price; price += 0.1) {
    std::cout << "Funds: " << total << " price of candy: " << price << std::endl;
    total -= price;
    cnt++;
  }
  std::cout << "\n\nCnt: " << cnt;
  std::cout << "\nReminder: " << total;
  return EXIT_SUCCESS;
}

// Funds: 1 price of candy: 0.10000000000000000555
// Funds: 0.9000000000000000222 price of candy: 0.2000000000000000111
// Funds: 0.69999999999999995559 price of candy: 0.30000000000000004441
// 
// 
// Cnt: 3
// Reminder: 0.39999999999999991118
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}