user2757651 user2757651 - 1 year ago 63
C Question

How would I print the largest possible float and double in C?

For the following code,

#include <stdio.h>
#include <limits.h>
#include <float.h>

int main(void) {
printf("double max = %??\n", DBL_MAX);
printf("double min = %??\n", DBL_MIN);
printf("double epsilon = %??\n", DBL_EPSILON);
printf("float epsilon = %??\n", FLT_EPSILON);
printf("float max = %??\n", FLT_MAX);
printf("float min = %??\n\n", FLT_MIN);
return 0;

what specifiers would I have to use in place of the ??'s in order for printf to display the various quantities as appropriately-sized decimal numbers?

Answer Source

Use the same format you'd use for any other values of those types:

#include <float.h>
#include <stdio.h>
int main(void) {
    printf("FLT_MAX = %g\n", FLT_MAX);
    printf("DBL_MAX = %g\n", DBL_MAX);
    printf("LDBL_MAX = %Lg\n", LDBL_MAX);

Arguments of type float are promoted to double for variadic functions like printf, which is why you use the same format for both.

%f prints a floating-point value using decimal notation with no exponent, which will give you a very long string of (mostly insignificant) digits for very large values.

%e forces the use of an exponent.

%g uses either %f or %e, depending on the magnitude of the number being printed.

On my system, the above prints the following:

FLT_MAX = 3.40282e+38
DBL_MAX = 1.79769e+308
LDBL_MAX = 1.18973e+4932

As Eric Postpischil points out in a comment, the above prints only approximations of the values. You can print more digits by specifying a precision (the number of digits you'll need depends on the precision of the types); for example, you can replace %g by %.20g.

Or, if your implementation supports it, C99 added the ability to print floating-point values in hexadecimal with as much precision as necessary:

printf("FLT_MAX = %a\n", FLT_MAX);
printf("DBL_MAX = %a\n", DBL_MAX);
printf("LDBL_MAX = %La\n", LDBL_MAX);

But the result is not as easily human-readable as the usual decimal format:

FLT_MAX = 0x1.fffffep+127
DBL_MAX = 0x1.fffffffffffffp+1023
LDBL_MAX = 0xf.fffffffffffffffp+16380

(Note: main() is an obsolescent definition; use int main(void) instead.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download