c - 避免 printf() 中的尾随零

标签 c printf

我一直在发现 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/

相关文章:

c - 找到(三次)多项式的实根的简单方法是什么?

C 错误 : undefined reference to function, 但已定义

c -\n 如何影响 scanf 中的字符串扫描?

c - 如何打印字符*

c++ - 在 C++ 中打印变量名的通用方法

c++ - 从另一个 exe 打开 exe,禁用内部 exe 中的某些键

c - 将 Dart 嵌入应用程序

c - 理解结构体

c - 在 C 中用 printf 打印字符不会打印

使用 snprintf 复制数组中的字符