Why the extra digits? 45.139999

Why is the output not consistent? How can we verify accuracy without having to use decimal places or double?

[code]#include <stdio.h>

int main(int argc, const char * argv[]) {
// This is a BNR Challenge.

// The challange first says to declare two variable of type float
// and assign each of them a number with a decimal point

float piNumber = 3.140;
float answerEverything = 42.0;

// Next, declare another variable of type double and assign it the sum of two floats

double sumFloats = piNumber + answerEverything;

// Next print the result using printf()

printf("The sum of the two floats is %f.\n", sumFloats);
printf("The sum with 2 decimal places is %.2f.\n", sumFloats);

// Setting smaller variables to see if the .9999 thing happens still

float testOne = 100.110;
float testTwo = 2.0;

double sumTests = testOne + testTwo;

printf("The test sum is %f.\n", sumTests);

//Of course, return 0
return 0;


[quote]Output: The sum of the two floats is 45.139999.
The sum with 2 decimal places is 45.14.
The test sum is 102.110001.[/quote]

When numbers of type float or double are encoded in binary by using a finite number of bits, sometimes there will be errors. This is unavoidable.

For more information, see the Wikipedia article http://en.wikipedia.org/wiki/Floating_point.

Thanks Ibex. A little ‘bit’ of a bummer - no pun intended…