DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Accuracy Issues With Floating Point Numbers In C++

08.15.2009
| 265 views |
  • submit to reddit
        
#include <iostream>
#include <cstdlib>
#include <iomanip>

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