float_t 和 double_t 格式说明符

float_t and double_t format specifiers

intN_t 类型有新的格式说明符,例如 %"PRIiN"%"SCNiN"printfscanf 函数族。

float_tdouble_t 的新格式说明符(如果有)是什么? (在 math.h 中定义)

我可以 - 安全地 - 使用 %f%lf 吗?我不这么认为,因为 float_t 至少和 float 一样大,但可以定义为 long double.

由于没有人回答,而且我在任何地方都找不到答案,这可能是 C 中的错误吗?

为了谨慎和便于携带,您可以在 printf 控制字符串中使用 %Lf,并将 float_tdouble_t 类型的值转换为 long double

已编辑: long double 的格式说明符是 %Lf 而不是 %lf

你必须对 scanf 更加谨慎,因为在那种情况下转换对你没有帮助。

或者,您可以为 float_tdouble_t 定义自己的 printfscanf 格式说明符,使用 FLT_EVAL_METHOD[1] 宏找出 float_tdouble_t 分别等同于哪些内置类型。

标准中不存在这些,因此您必须使用 FLT_EVAL_METHOD (C11 7.12.2) 自己定义它们。

我将分享我在我的库中为此编写的代码:

#if (FLT_EVAL_METHOD == 0)
#define PRIaFLT     "a"
#define PRIAFLT     "A"
#define PRIeFLT     "e"
#define PRIEFLT     "E"
#define PRIfFLT     "f"
#define PRIFFLT     "F"
#define PRIgFLT     "g"
#define PRIGFLT     "G"

#define SCNaFLT     "a"
#define SCNeFLT     "e"
#define SCNfFLT     "f"
#define SCNgFLT     "g"

#define PRIaDBL     "la"
#define PRIADBL     "lA"
#define PRIeDBL     "le"
#define PRIEDBL     "lE"
#define PRIfDBL     "lf"
#define PRIFDBL     "lF"
#define PRIgDBL     "lg"
#define PRIGDBL     "lG"

#define SCNaDBL     "la"
#define SCNeDBL     "le"
#define SCNfDBL     "lf"
#define SCNgDBL     "lg"


#elif   (FLT_EVAL_METHOD == 1)
#define PRIaFLT     "la"
#define PRIAFLT     "lA"
#define PRIeFLT     "le"
#define PRIEFLT     "lE"
#define PRIfFLT     "lf"
#define PRIFFLT     "lF"
#define PRIgFLT     "lg"
#define PRIGFLT     "lG"

#define SCNaFLT     "la"
#define SCNeFLT     "le"
#define SCNfFLT     "lf"
#define SCNgFLT     "lg"

#define PRIaDBL     "la"
#define PRIADBL     "lA"
#define PRIeDBL     "le"
#define PRIEDBL     "lE"
#define PRIfDBL     "lf"
#define PRIFDBL     "lF"
#define PRIgDBL     "lg"
#define PRIGDBL     "lG"

#define SCNaDBL     "la"
#define SCNeDBL     "le"
#define SCNfDBL     "lf"
#define SCNgDBL     "lg"


#elif   (FLT_EVAL_METHOD == 2)
#define PRIaFLT     "La"
#define PRIAFLT     "LA"
#define PRIeFLT     "Le"
#define PRIEFLT     "LE"
#define PRIfFLT     "Lf"
#define PRIFFLT     "LF"
#define PRIgFLT     "Lg"
#define PRIGFLT     "LG"

#define SCNaFLT     "La"
#define SCNeFLT     "Le"
#define SCNfFLT     "Lf"
#define SCNgFLT     "Lg"

#define PRIaDBL     "La"
#define PRIADBL     "LA"
#define PRIeDBL     "Le"
#define PRIEDBL     "LE"
#define PRIfDBL     "Lf"
#define PRIFDBL     "LF"
#define PRIgDBL     "Lg"
#define PRIGDBL     "LG"

#define SCNaDBL     "La"
#define SCNeDBL     "Le"
#define SCNfDBL     "Lf"
#define SCNgDBL     "Lg"
#endif

然后你应该可以做到:

double_t    x;

scanf(" %"SCNaDBL"", &x);
printf("x = %"PRIaDBL"\n", x);