我一直在发现 printf() 系列函数的格式说明符。我想要的是能够打印小数点后最大给定位数的 double (或 float )。如果我使用:
printf("%1.3f", 359.01335);
printf("%1.3f", 359.00999);
我明白了
359.013
359.010
而不是想要的
359.013
359.01
有人可以帮我吗?
最佳答案
这不能用普通的 printf
格式说明符来完成。您可以获得的最接近的结果是:
printf("%.6g", 359.013); // 359.013
printf("%.6g", 359.01); // 359.01
但是“.6”是总数字宽度,所以
printf("%.6g", 3.01357); // 3.01357
破坏它。
您可以做的是将sprintf("%.20g")
数字写入字符串缓冲区,然后操作该字符串,使其仅包含小数点后的N个字符.
假设您的数字位于变量 num 中,以下函数将删除除前 N
个小数之外的所有小数,然后去掉尾随的零(如果全部为零,则去掉小数点)。
char str[50];
sprintf (str,"%.20g",num); // Make the number.
morphNumericString (str, 3);
: :
void morphNumericString (char *s, int n) {
char *p;
int count;
p = strchr (s,'.'); // Find decimal point, if any.
if (p != NULL) {
count = n; // Adjust for more or less decimals.
while (count >= 0) { // Maximum decimals allowed.
count--;
if (*p == '\0') // If there's less than desired.
break;
p++; // Next character.
}
*p-- = '\0'; // Truncate string.
while (*p == '0') // Remove trailing zeros.
*p-- = '\0';
if (*p == '.') { // If all decimals were zeros, remove ".".
*p = '\0';
}
}
}
<小时/>
如果您对截断方面不满意(这会将 0.12399
转换为 0.123
,而不是四舍五入为 0.124
),您实际上可以使用 printf 已经提供的舍入功能。您只需要预先分析数字以动态创建宽度,然后使用它们将数字转换为字符串:
#include <stdio.h>
void nDecimals (char *s, double d, int n) {
int sz; double d2;
// Allow for negative.
d2 = (d >= 0) ? d : -d;
sz = (d >= 0) ? 0 : 1;
// Add one for each whole digit (0.xx special case).
if (d2 < 1) sz++;
while (d2 >= 1) { d2 /= 10.0; sz++; }
// Adjust for decimal point and fractionals.
sz += 1 + n;
// Create format string then use it.
sprintf (s, "%*.*f", sz, n, d);
}
int main (void) {
char str[50];
double num[] = { 40, 359.01335, -359.00999,
359.01, 3.01357, 0.111111111, 1.1223344 };
for (int i = 0; i < sizeof(num)/sizeof(*num); i++) {
nDecimals (str, num[i], 3);
printf ("%30.20f -> %s\n", num[i], str);
}
return 0;
}
在这种情况下,nDecimals()
的全部意义在于正确计算出字段宽度,然后使用基于此的格式字符串格式化数字。测试工具 main()
显示了这一点:
40.00000000000000000000 -> 40.000
359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.010
359.00999999999999090505 -> 359.010
3.01357000000000008200 -> 3.014
0.11111111099999999852 -> 0.111
1.12233439999999995429 -> 1.122
一旦获得正确舍入的值,您可以再次将其传递给 morphNumericString()
,只需更改即可删除尾随零:
nDecimals (str, num[i], 3);
进入:
nDecimals (str, num[i], 3);
morphNumericString (str, 3);
(或者在 nDecimals
末尾调用 morphNumericString
但在这种情况下,我可能只是将两者合并为一个函数),最终得到:
40.00000000000000000000 -> 40
359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.01
359.00999999999999090505 -> 359.01
3.01357000000000008200 -> 3.014
0.11111111099999999852 -> 0.111
1.12233439999999995429 -> 1.122
关于c - 避免 printf() 中的尾随零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27214395/