在 printf 格式字符串中使用非标准的 apostrophe 标志,如果您有该选项可用并且不介意失去一点可移植性。
根据我的文档,' 标志自 1997 年以来可用于 POSIX 系统。
如果您使用的是 Unix、Linux、Mac,... 应该没问题
如果你在 Windows、DOS、iSeries、Android 上……所有的赌注都没有了(但也许你可以在你的系统上安装一个 POSIX 层)。
#include <locale.h>
#include <stdio.h>
int main(void) {
long int x = 130006714000000;
setlocale(LC_NUMERIC, "en_US.utf-8"); /* important */
while (x > 0) {
printf("# %%'22ld: %'22ld\n", x); /* apostrophe flag */
x *= 2; /* on my machine, the Undefined Behaviour for overflow
// makes the number become negative with no ill effects */
}
return 0;
}
在我的系统上这个程序产生:
# %'22ld: 130,006,714,000,000
# %'22ld: 260,013,428,000,000
# %'22ld: 520,026,856,000,000
# %'22ld: 1,040,053,712,000,000
# %'22ld: 2,080,107,424,000,000
# %'22ld: 4,160,214,848,000,000
# %'22ld: 8,320,429,696,000,000
# %'22ld: 16,640,859,392,000,000
# %'22ld: 33,281,718,784,000,000
# %'22ld: 66,563,437,568,000,000
# %'22ld: 133,126,875,136,000,000
# %'22ld: 266,253,750,272,000,000
# %'22ld: 532,507,500,544,000,000
# %'22ld: 1,065,015,001,088,000,000
# %'22ld: 2,130,030,002,176,000,000
# %'22ld: 4,260,060,004,352,000,000
# %'22ld: 8,520,120,008,704,000,000