Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Accuracy Issues With Floating Point Numbers In C

DZone's Guide to

Accuracy Issues With Floating Point Numbers In C

·
Free Resource

#include 
  
   
#include 
   
    

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


   
  
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}