Problem accurate to% g

When I used printf("%.6g\n",36.666666662); I was expecting 36.666667 exit. But the actual conclusion is 36.6667

What is wrong with the format I gave? My goal is to have 6 decimal digits

+6
source share
1 answer

This is the correct behavior.

For qualifiers a, A, e, E, f, and F: this is the number of digits to be printed after the decimal point.

For qualifiers g and G: this is the maximum number of significant digits to print. A.

If you use f instead of g , then it will work as you expected.


Code example

 #include <stdio.h> int main(void) { printf("%.6g\n", 36.666666662); printf("%.6f\n", 36.666666662); return 0; } 

Result

 36.6667 36.666667 

See how it works on the Internet: ideone .

+11
source

All Articles