I'm new in C language, but I've tried integer, float and double division in C as I'm normally doing in Java, but when I execute 5.0/3 instead of 1.6666666666666667 I'm getting 1.666667 for double division and for float division.
I had tried to execute the program using Visual Studio as I always do but I got the message "First number is 1, second one is 1.666667 and the last one is 1.666667." after executing:
#include <stdio.h>
int main()
{
int firstNumber = 5 / 3;
float secondNumber = 5.0f / 3.0f;
double thirdNumber = 5.0 / 3.0;
printf("First number is %d, second one is %f and the last one is %lf.", firstNumber, secondNumber, thirdNumber);
return 0;
}
Why I'm getting the same result for 'secondNumber' and for 'thirdNumber'?
Typical float
can represent about 232 different values.
Typical double
can represent about 264 different values.
In both types, 5/3, the exact quotient of the division, is not in that set. Instead a nearby value (some binary fraction) is used.
float secondNumber = 5.0f / 3.0f; // 1.66666662693023681640625
double thirdNumber = 5.0 / 3.0; // 1.6666666666666667406815349750104360282421112060546875
When using "%f"
, 6 places past the decimal point are used. The printed text is a rounded one. In both cases, rounding to the same.
1.666667
To see more digits, use "%.10f"
, "%.20f"
, etc. @xing
printf("%.10f\n", secondNumber);
printf("%.10f\n", thirdNumber);
Output
1.6666666269
1.6666666667