PAT_A 1001 A+B Format
PAT_A 1001 A+B Format
分析
本题需要将A+B的结果转换为由 ,
分割的数字,即从个位向前,每输出三个数字就需要一个 ,
分割,若没有数字则不输出,
;若错误的话,可以多输入几个数字看一下。
题目的描述
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 Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where \(−10^6≤a,\ b≤10^6\). The numbers are separated by a space.
Output Specification:
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 9
Sample Output:
-999,991
AC的代码
#include<bits/stdc++.h>
using namespace std;
int main(){
long long a,b;
cin>>a>>b;
a+=b;
if(a<0){
cout<<'-';
a=-a;
}
string as = to_string (a);
b = as.length()%3;
for(int i=0;i<as.length();i++){
if(!b){
if(i)cout<<',';
b=2;
}
else {
b--;
}
cout<<as[i];
}
cout<<endl;
return 0;
}
本文来自博客园,作者:ghosteq,转载请注明原文链接:https://www.cnblogs.com/ghosteq/p/15841280.html