您的位置:首页 > 编程语言

编程题目:PAT(Advanced Level) Practice 1001. A+B Format (20)

2014-07-13 12:52 609 查看


1001. A+B Format (20)

时间限制

400 ms

内存限制

32000 kB

代码长度限制

16000 B

判题程序

Standard

作者

CHEN, Yue

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 9

Sample Output
-999,991

       本题并不难,要注意的就是对于输出格式的控制。参考代码如下,其实写的有些繁琐了,直接借助1000这个值来控制输出应该更便捷。
/* http://pat.zju.edu.cn/contests/pat-a-practise/1001 */

#include<iostream>
#include<vector>
#include<stack>
using namespace std;

int main()
{
stack<int> v;
int a ,b ;
cin>>a>>b;
int c= a + b;
int sign=0;
if( c==0 )//等于0
{
cout<<"0"<<endl;
}
if(c<0)//负数的处理
{
sign = 1;//表负数
c = 0-c;
}
while(c!=0)
{
int temp = c%10;
v.push(temp);
c/=10;
}

///控制输出
if(sign==1)
cout<<'-';
int remind = v.size()%3;
int flag = 0;
while(remind>0)
{
flag = 1;
int out = v.top();
cout<<out;
v.pop();
remind--;
}
if(flag ==1 && !v.empty())
cout<<',';
int count = 0;
while(!v.empty())
{
if(count%3==0 && count>0)
cout<<",";
int out = v.top();
cout<<out;
v.pop();
count++;

}

system("pause");
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PAT Advanced level 1001