C++中如何将用户输入的一个不确定的正整数按照标准的三位分节格式输出,如8266864,输出为:82,668,634

2025-01-06 09:39:06
推荐回答(3个)
回答1:

请参考如下的代码,要转换的数放在变量i中。
const unsigned SECTION_COUNT = 3;
int i = 1234;
char buf[512];
_itoa(i, buf, 10);
unsigned len = strlen(buf);
unsigned pCnt = (len - 1) / SECTION_COUNT;
unsigned fix = len % SECTION_COUNT;
buf[len + pCnt] = '\0';
while (pCnt)
{
char* pos = buf + (pCnt - 1) * SECTION_COUNT + fix;
memmove(pos + pCnt, pos, SECTION_COUNT);
pos[--pCnt] = ',';
}

回答2:

不停的%10和/10,每3个一输出,为0结束

回答3:

CString str;
输入X
b = X % 1000;
X = X / 1000;
str = Format(b)
while X>0
Do
b=X % 1000
X = X / 1000
str = "," + str
if X > 0 Then
str = Format(b) + str // 带0前缀
else
str = Format(b) + str // 不带0前缀
End