gpt4 book ai didi

c - Printf 可变浮点型小数位数

转载 作者:行者123 更新时间:2023-11-30 16:07:19 27 4
gpt4 key购买 nike

我发现打印非终止固定长度字符串的有趣格式,如下所示:

char newstr[40] = {0};
sprintf(newstr,"%.*s", sizeof(mystr), mystr);

所以我想也许有一种方法可以在 printf 命令下打印 float ......

"%8.2f"

能够选择整数的小数位数。

类似这样的事情:

sprintf(mystr, "%d %f", numberofdecimals, floatnumbervalue)

最佳答案

您还可以将".*"与浮点一起使用,另请参阅http://www.cplusplus.com/reference/cstdio/printf/(指C++,但格式说明符类似)

.number: For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).

...

.*: The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

例如:

float floatnumbervalue = 42.3456;
int numberofdecimals = 2;
printf("%.*f", numberofdecimals, floatnumbervalue);

输出:

42.35

关于c - Printf 可变浮点型小数位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59681757/

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