gpt4 book ai didi

c - printf 在一定程度上跟随零

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

我正在尝试打印一定长度的零以与存储为字符串的另一个数字进行比较,我想知道该怎么做?

编辑:添加示例代码
例如:

printf("%s\n", "References:\n3.141592653"
"58979323846264338327950288419716939937510582097494459230781640628620899");
printf("Monte Carlo: %d nodes over %d iterations calculated Pi as:\n%1.9f\n", numnodes,
final_iters,pi); //Print the calculated value of pi

输出是

References:
3.14159265358979323846264338327950288419716939937510582097494459230781640628620899
Monte Carlo 16 nodes over 160000 iterations calculated Pi as:
3.142025000

如何让实际计算在字符串末尾填入零?

最佳答案

How would I make the actual calculation fill in zeros to the end of the string?

代码可以尝试各种数字方法,例如

printf("%1.9f%071d\n", pi, 0); // Print an extra int 0 with wide width padded with '0'
printf("%1.80f\n", pi); // Print with wide precision - (might not all be 0's)

但我担心具有较大宽度/精度的说明符和数字说明符可能会破坏某些 printf() 实现。所以我将添加一个文本方法。

#define PI_STR "3.1415926535" \
"8979323846264338327950288419716939937510582097494459230781640628620899"
printf("%s\n", "References:\n" PI_STR);

// Remember length of reference pi string
int pi_ref_len = (sizeof PI_STR) - 1;

...
// Print computed pi & return count of characters printed
int pi_compute_len = printf("%1.9f", pi);

// Use a loop or print a portion of a string "0000...000"
char zeros[sizeof PI_STR];
memset(zeros, '0', sizeof zeros);
// v--- %s w/precision can print a non-null character terminated char array
printf("%.*s\n", pi_ref_len - pi_compute_len, zeros);

关于c - printf 在一定程度上跟随零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53111724/

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