计算A+B的和,以每三位加一个 " , " 的格式输出,-10^6 <= A , B <= 10^6
(1) 利用字符数组
#include<iostream>
using namespace std;
int main(){
int a,b,sum;
char s[10];
cin >> a >> b;
sum = a + b;
if(sum==0){
cout << 0;
return 0;
}
else if(sum<0){
sum = -sum;
cout << '-';
}
int i=0;
while(sum){
s[i++] = '0'+ sum % 10;
sum /= 10;
}
s[i] = '\0';
i--;
while(i>=0){
cout << s[i];
if(i!=0 && i%3==0) cout << ',';
i--;
}
}
(2) 利用to_string函数
将数字常量转换为字符串,并返回对应的字符串
#include <iostream>
using namespace std;
int main() {
int a,b,sum;
cin >> a >> b;
sum = a + b;
if(sum<0){
sum = -sum;
cout << '-';
}
string s = to_string(sum);
int len = s.length();
for (int i = 0; i < len; i++) {
cout << s[i];
if ((len-1-i)%3==0 && i != len - 1) cout << ",";
}
}