2

次のコードでは、

#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;
}

printf がさまざまな量を適切なサイズの 10 進数として表示するには、?? の代わりにどの指定子を使用する必要がありますか?

4

3 に答える 3

7

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.)

于 2013-09-14T01:29:32.123 に答える
1

実際の値を表すのに十分な桁数で最大値の近似値を出力するには (出力された値を浮動小数点に変換した結果が元の値になるはずです)、次を使用できます。

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


int main(void)
{
    printf("%.*g\n", DECIMAL_DIG, FLT_MAX);
    printf("%.*g\n", DECIMAL_DIG, DBL_MAX);
    printf("%.*Lg\n", DECIMAL_DIG, LDBL_MAX);
    return 0;
}

FLT_DECIMAL_DIGC 2011 では、より具体的な、DBL_DECIMAL_DIG、およびLDBL_DECIMAL_DIGを の代わりに使用できますDECIMAL_DIG

近似値ではなく正確な値を出力するには、さらに精度を指定する必要があります。(int) (log10(x)+1)桁数で十分です。

最小値とイプシロンの近似は、同じ方法で十分な精度で出力できます。ただし、正確な値に必要な桁数の計算は、最大値よりも複雑になる場合があります。(技術的には、エキゾチックな C 実装では不可能かもしれません。たとえば、基数 3 の浮動小数点システムでは、有限の 10 進数では表現できない最小値が存在します。私は、そのような実装が使用されていることを知りません。)

于 2013-09-14T03:09:49.027 に答える