printf("num1(%s), num2(%s), num3(%s)\n", format_thousands_separator(0),format_thousands_separator(123456),format_thousands_separator(23456789));
注:要求寫出可編譯并可以運行通過的程序代碼。
經過修改后,我目前最簡潔的C代碼描述如下
1
char* format_thousands_separator(unsigned long val)
2
{
3
static char buf[16][16];
4
static int c = 0;
5
6
long m, n = 0;
7
char* p = &buf[c++ % 16][15];
8
*p = '\0';
9
10
do
11
{
12
m = val % 10;
13
val = val / 10;
14
*--p = '0' + m;
15
16
if (val && !(++n % 3))
17
*--p = ',';
18
19
} while(val);
20
21
return p;
22
}
char* format_thousands_separator(unsigned long val)2
{3
static char buf[16][16];4
static int c = 0;5
6
long m, n = 0;7
char* p = &buf[c++ % 16][15];8
*p = '\0';9
10
do 11
{12
m = val % 10;13
val = val / 10;14
*--p = '0' + m;15

16
if (val && !(++n % 3))17
*--p = ',';18

19
} while(val);20

21
return p;22
} 這里再稍作一下擴展,使之能支持負數,代碼描述如下
1
char* format_thousands_separator(long val)
2
{
3
static char buf[16][16];
4
static int c = 0;
5
6
long m, n = 0;
7
char* p = &buf[c++ % 16][15];
8
*p = '\0';
9
10
do
11
{
12
m = val % 10;
13
val = val / 10;
14
*--p = '0' + (m < 0 ? -m : m);
15
16
if (!val && m < 0)
17
*--p = '-';
18
19
if (val && !(++n % 3))
20
*--p = ',';
21
22
} while(val);
23
24
return p;
25
}
char* format_thousands_separator(long val)2
{3
static char buf[16][16];4
static int c = 0;5
6
long m, n = 0;7
char* p = &buf[c++ % 16][15];8
*p = '\0';9
10
do 11
{12
m = val % 10;13
val = val / 10;14
*--p = '0' + (m < 0 ? -m : m);15

16
if (!val && m < 0) 17
*--p = '-';18

19
if (val && !(++n % 3))20
*--p = ',';21
22
} while(val);23

24
return p;25
} 如果哪位大俠有更簡潔高效的代碼,還望留言或Email我,謝謝哈



