subha
subha

Reputation: 133

Float values differs while printing the assigned value and the computed value in C

I could see one issue with GCC Compiler while doing the division operation.

Code:

#include <stdio.h>
int main() {
   unsigned char a = 81;
   float value_1 = a / 255.; 
   float value_2 = (float)a / 255.0; 
   printf("%.12f----->%.12f -----> %.12f", value_1, value_2, a/255.);
   return 0;
}

Results:

0.317647069693----->0.317647069693 -----> 0.317647058824

I could see that results are differing while printing the assigned values and the computed values at the sixth precision. Why it happens?

Upvotes: 0

Views: 65

Answers (2)

Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27652

The first two values are single-precision floating-point values, and the final one is a double-precision value. If you print them with more decimals you will see the difference, for example like this:

0.3176470696926116943359375000000000000000000000000000000000000000000000
0.3176470696926116943359375000000000000000000000000000000000000000000000
0.3176470588235293934786795944091863930225372314453125000000000000000000

Remember that the standard floating-point type in C is double, not float. A floating-point constant, such as your 255., has the type double, not float. So the final argument to printf, a/255., will be calculated using double precision, and sent to printf as a double. The variables value_1 and value_2 are of type float, and even though they are converted to double when sent to printf, they have fewer binary digits.

Upvotes: 7

Abhishek Keshri
Abhishek Keshri

Reputation: 3244

First two are floats while last one is a double. double has 2x more precision than float.

Single precision (float) gives you 23 bits of significand, 8 bits of exponent, and 1 sign bit.

Double precision (double) gives you 52 bits of significand, 11 bits of exponent, and 1 sign bit.

Upvotes: 0

Related Questions