PTA 1001 A+B Format
Posted jarvis-yang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PTA 1001 A+B Format相关的知识,希望对你有一定的参考价值。
问题描述:
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 −. 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
没啥难的,水一篇罢了,帮狗子同学改的代码,缩进没改。
代码:
1 #include <iostream> 2 #include <cmath> 3 using namespace std; 4 int main() 5 { 6 int a,b,sum=0; 7 long x; 8 char num[30]={}; 9 cin>>a>>b; 10 x=a+b; 11 if (x>0){ 12 while (x!=0) 13 { 14 num[sum]=x%10+48; 15 x=x/10; 16 sum++; 17 } 18 for (int i=sum-1;i>=0;i--) 19 { 20 cout<<num[i]; 21 if (i%3==0&&i!=0) 22 cout<<","; 23 }} 24 else if (x==0) 25 cout<<"0"; 26 else 27 { 28 while (x!=0) 29 { 30 num[sum]=abs(x%10)+48; 31 x=x/10; 32 sum++; 33 } 34 cout<<"-"; 35 for (int i=sum-1;i>=0;i--) 36 { 37 cout<<num[i]; 38 if (i%3==0&&i!=0) 39 cout<<","; 40 }} 41 return 0; 42 }
以上是关于PTA 1001 A+B Format的主要内容,如果未能解决你的问题,请参考以下文章