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 −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
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
int a,b;
while(scanf("%d%d",&a,&b)==2)
{
int c=a+b;
char ans[9];//-1000000
sprintf(ans,"%d",c);////把整数c 打印成一个字符串保存在ans中。头文件:cstdio
char res[10];//-1,000,000
memset(res,0,sizeof(res));//将res中当前位置后面的sizeof(res)个字节 用 0 替换并返回 res ,相当于初试化res数组.头文件:cstring
int len=strlen(ans);
int j=0;
int cnt=0;
for(int i=len-1;i>=0;i--)//因为输出是从后往前每三个数一个逗号,所以要借助数组res,逆序保存结果 ,再反转数组最后输出
{
res[j++]=ans[i];
cnt++;
if(ans[i-1]>='0'&&ans[i-1]<='9' && cnt%3==0)
{
res[j++]=',';
}
}
reverse(res,res+j);//reverse(res[0],res[j]) 可以将数组指针在[0,j)之间的元素范围内的元素进行反转 头文件:algorithm
printf("%s\n",res);
}
return 0;
}
F2:借助栈先进后出的特点
#include<cstdio>
#include<stack>
using namespace std;
int main()
{
int a,b,st;
scanf("%d%d",&a,&b);
st = a + b;
int i = 0;
if(st<1000 && st>-1000)//若为三位数则直接输出
{
printf("%d\n",st);
return 0;
}
if(st < 0)
{
printf("-");
st=-st;
}
stack<int> sta;//建立一个栈,栈为先进后出 ,头文件<stack>
while(st>0)
{
i++;
sta.push(st%10);//个位数依次进栈
st=st/10;
}
while(!sta.empty())
{
i--;
printf("%d",sta.top());//输出栈顶元素
if(i!=0&&i%3==0)
printf(",");
sta.pop();//将栈顶元素删除
}
printf("\n");
return 0;
}