顽强的小白
1001 A+B Format (20 分)
题目
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 −106≤a,b≤106. 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
代码实现
#include <cstdio>
#include <cstring>
using namespace std;
void deal(int num){
char pp[20],temp;
int t,i=0;
if(num<0){
printf("-");
num=-num;
}
int cnt=1;
while(num!=0){
t=num%10;
pp[i++]=t+'0';
num=num/10;
if(cnt%3==0&&num!=0){
pp[i++]=',';
}
cnt++;
}
for(int j=i-1;j>=0;--j){
printf("%c",pp[j]);
}
}
int main(){
int a,b,sum;
scanf("%d %d",&a,&b);
sum=a+b;
deal(sum);
}
注意点
既然是学习日志,我就的记得详细点,有点啰嗦也认了,希望自己后面再来看看
- 第一个测试点分值最大;
- 负数的处理简单明了;
- 计算不是难点,(其实这道题不难)主要是输出,要把数字按照每三位输出一个逗号,我把数字转换成了字符串储存起来,然后把逗号加进去,因为在转换成字符的时候用的最常用的除余数法,得到的结果是倒着的,因此正好符合加逗号的规则(逗号是从个位向高位数着加的),最后不能在最前面加逗号,也确实有这个测试点,注意看我加了一个条件sum!=0
字符串成形之后倒着输出就行啦,不需要逆转; - 结果为零的输出要单独处理,只要注意到就没什么事了;