Calculate a + b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits).
Input
Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.
Output
For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.
Sample Input-1000000 9Sample Output
-999,991
给定条件:
1.两个数字a和b
要求:
1.算出a+b
2.输出的经过每三位加一个逗号
求解:
方法1.从左往右来,如果当前位置是第四个,即三的倍数(从0开始)就输出逗号
方法2.从右往左来,每三个数字加一个逗号
#include <cstdio>
#include <cstring>
using namespace std;
int a, b, c;
char num[10];
int main() {
scanf("%d%d", &a, &b);
c = a + b;
sprintf(num,"%d", c);
int len = strlen(num);
for(int i = 0; i < len; i++) {
printf("%c", num[i]);
if(num[i] == '-') continue;
if((len-i-1) % 3 == 0 && i != len-1) {
printf(",");
}
}
printf("\n");
return 0;
}
#include <cstdio>
#include <vector>
using namespace std;
int a, b, c;
vector<char> v;
int main() {
scanf("%d%d", &a, &b);
c = a + b;
int cnt = 0;
if(c < 0){
c *= -1;
printf("-");
}
while(c > 0) {
char temp = '0' + c % 10;
v.push_back(temp);
cnt++;
if(cnt % 3 == 0) {
v.push_back(',');
}
c /= 10;
}
if(v.size() == 0){
printf("0\n");
return 0;
}
if(v[v.size()-1] == ',') v.pop_back();
for(int i = v.size()-1; i >= 0; i--) {
printf("%c", v[i]);
}
return 0;
}