标签:ensure htm scanf cas pair cstring sum less one
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).
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.
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.
-1000000 9
-999,991
两种思路,第一种是今天写的,将结果预处理好存在字符串里直接输出
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 using namespace std; 5 int main() 6 { 7 long long a,b,c; 8 char s[100]; 9 while(scanf("%lld%lld",&a,&b)!=EOF) 10 { 11 c=a+b; 12 int flag=0; 13 if(c<0) 14 { 15 flag=1; 16 c=0-c; 17 } 18 int l=0; 19 int g,w=0; 20 while(c) 21 { 22 g=c%10; 23 c/=10; 24 s[l++]=g+‘0‘; 25 w++; 26 if(w%3==0)s[l++]=‘,‘; 27 } 28 if(a+b==0)cout << "0" <<endl; 29 else 30 { 31 if(flag)cout <<"-"; 32 if(s[l-1]!=‘,‘)cout << s[l-1]; 33 for(int i=l-2;i>=0;i--) 34 cout << s[i]; 35 cout <<endl; 36 } 37 } 38 }
另一种是去年写的,一边输出一边加逗号,翻看以前的代码被自己秀到了。。。
1 #include<iostream> 2 #include<cstdio> 3 #include<cmath> 4 using namespace std; 5 int main() 6 { 7 int a,b,c,d=1; 8 while(scanf("%d%d",&a,&b)!=EOF) 9 { 10 a+=b; 11 c=0; 12 d=1; 13 if(a<0){printf("-"); a=0-a;} 14 b=a; 15 while(a/=10) 16 { 17 c++; 18 d*=10; 19 } 20 c++; 21 for(;c>0;) 22 { 23 printf("%d",b/d); 24 b%=d; 25 d/=10; 26 c--; 27 if(!(c%3)&&c)printf(","); 28 } 29 printf("\n"); 30 } 31 return 0; 32 }
标签:ensure htm scanf cas pair cstring sum less one
原文地址:https://www.cnblogs.com/LowBee/p/10439147.html