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
| 154 views |
  • submit to reddit
        
#include <stdio.h>
#include <stdlib.h>

int main(void) {
  double total = 1, price;
  int cnt = 0;
  for(price = 0.1; total >= price; price += 0.1) {
    printf("Funds: %0.17f, price of candy: %0.17f\n", total, price);
    total -= price;
    cnt++;
  }
  printf("\n\nCnt: %d", cnt);
  printf("\nReminder: %.17f", total);
  return EXIT_SUCCESS;
}

// Funds: 1.00000000000000000, price of candy: 0.10000000000000001
// Funds: 0.90000000000000002, price of candy: 0.20000000000000001
// Funds: 0.69999999999999996, price of candy: 0.30000000000000004
// 
// 
// Cnt: 3
// Reminder: 0.39999999999999991

    
    Tags:
  • C