C对我来说是一门外语,我凭直觉尝试将数字划分为数字。(我没有找到执行此操作的标准机会或标准库中的任何功能)
为什么第一次调用的结果是正确的,但第二次调用的结果却是一些垃圾,这对我来说仍然是个谜。
怎么修?
#include <stdio.h>
#include <locale.h>
char* intToStrWithThousandsSep(unsigned long long n)
{
static int comma = '\0';
static char retbuf[30];
char *p = &retbuf[sizeof(retbuf) - 1];
int i = 0;
if (comma == '\0') {
struct lconv *lcp = localeconv();
if(lcp != NULL) {
if(lcp->thousands_sep != NULL &&
*lcp->thousands_sep != '\0')
comma = *lcp->thousands_sep;
else
comma = '.';
}
}
*p = '\0';
do {
if(i%3 == 0 && i != 0)
*--p = comma;
*--p = '0' + n % 10;
n /= 10;
i++;
} while(n != 0);
return p;
}
int main() {
int m;
for(int i = 1; i < 11; i++){
m = i * i * i * 1111111;
printf("%5d %16s %16s\n", i, intToStrWithThousandsSep(m), intToStrWithThousandsSep(m * 10));
}
return 0;
}
为了消除 Harry 描述的错误,我将其重写如下:
和
现在输出
i < 6
是正确的。当i = 6
我们m*10
等于 2399999760 时,这完全符合int
- 因此在第二列中的所有废话i >= 6
。您的函数接受的内容
unsigned long long
并m
不能阻止它成为正常的int
.