初次做法:每次取三位存一下再按顺序格式输出,相对通用化。
学习到了C和C++不同的格式输出方法。
C: printf("%03d",a); //三位数,以0前导填充
C++: cout << setw(3) << setfill(‘0’) << a ;
int main(void)
{
io
int a,b;
cin >> a >> b;
int c = a + b;
if(c < 0) {
cout << "-";
c = -c;
}
std::vector<int> v;
while(c)
{
v.push_back(c%1000);
c/=1000;
}
int len = (int)v.size();
if(!len) {
cout << "0" << endl;
return 0;
}
cout << v[len-1];
for (int i = len - 2; i>=0 ; i--)
{
cout << "," << setw(3) << setfill('0') << v[i];
}
cout << endl;
return 0;
}
方法二:
数据范围过小,分三种情况讨论即可
int main(void)
{
int a = read(), b = read();
int c = a + b;
if(c<0) {
cout << '-';
c = -c;
}
if(c<1000) cout << c << endl;
else if(c >= 1000 && c < 1000000)
cout << c/1000 << "," << setw(3) << setfill('0') << c%1000 << endl;
else
cout << c/1000000 << "," << setw(3) << setfill('0') << (c%1000000)/1000 << "," << setw(3) << setfill('0') << c%1000 << endl;
}