gpt4 book ai didi

c - printf 的参数用作格式说明符的参数

转载 作者:太空宇宙 更新时间:2023-11-04 05:33:26 24 4
gpt4 key购买 nike

假设我有以下功能:

void fprint(float f, int ds) {
printf("%.%df\n", ds, f);
}

我希望调用者指定要打印的 float ,以及小数点后的位数。 (由 .%d 说明符指示)

但是,编译时我收到 2 个警告:

./sprint.h: In function ‘fprint’:
./sprint.h:19:14: warning: conversion lacks type at end of format [-Wformat=]
printf("%.%df\n", ds, f);
^

./sprint.h:19:12: warning: too many arguments for format [-Wformat-extra-args]
printf("%.%df\n", ds, f);
^~~~~~~~~

当调用它时:fprint(3.1422223f, 3);,它会产生输出:%df。我还尝试交换函数声明中参数的顺序,但它会产生相同的警告。

我的问题是:如何将格式说明符(例如本例中的 %d)注入(inject)现有格式说明符?

最佳答案

您可以在 printf 中使用星号来指定宽度或精度由参数给出——无需创建动态格式字符串。

printf("%.*f", ds, f);

手册页的 printf(3):

Precision

An optional precision, in the form of a period (.) followed by an optional decimal digit string. Instead of a decimal digit string one may write * or *m$ (for some decimal integer m) to specify that the precision is given in the next argument, or in the m-th argument, respectively, which must be of type int. If the precision is given as just ., the precision is taken to be zero. A negative precision is taken as if the precision were omitted. This gives the minimum number of digits to appear for d, i, o, u, x, and X conversions, the number of digits to appear after the radix character for a, A, e, E, f, and F conversions, the maximum number of significant digits for g and G conversions, or the maximum number of characters to be printed from a string for s and S conversions.

关于c - printf 的参数用作格式说明符的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51140390/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com