http://pat.zju.edu.cn/contests/pat-a-practise/1001
此题花费了很长时间,做了几次都是说超时,网上找了个答案找到毛病,while(true)是绝对不能用的,while(cin>>a>>b)可以用。
#include <cstdlib> #include <iostream> #include <string> #include <algorithm> using namespace std; int main(int argc, char *argv[]) { int a,b,sum,n,i; n=1,i=1; cin>>a>>b; sum=a+b; //cout<<sum<<endl; bool isneg=false; if(sum<0) { isneg=true; sum=0-sum;//不用abs()函数了 } string str; while(sum) { char ch='0'+sum%10; sum/=10; if(i%4==0) { str.push_back(','); i=1; } str.push_back(ch); i++; } reverse(str.begin(),str.end()); if(isneg) { cout<<'-'; } cout<<str<<endl; system("PAUSE"); return EXIT_SUCCESS; }
#include<iostream> #include<cmath> using namespace std; int main(){ long a,b,c; int i,flag; bool is_positive; char result[9]; while(cin>>a>>b) { c = a+b; if( c>0 ) is_positive = true; else is_positive = false; flag = 0; if(abs(c) >= 1000){ c = abs(c); //取绝对值 for( i=0; c>0; i++){ result[i] = c%10 + '0'; //数字转换成字符 c = c/10; if(flag == 2 && c != 0 ) { i++; result[i] = ','; //每三个加一个逗号 flag = 0; } else flag++; } if( !is_positive ) //结果为负数时 { result[i] = '-'; cout<<result[i]; } i--; //i指向第一个数字 for(; i>=0; i--){ cout<<result[i]; } cout<<endl; } else { cout<<c<<endl; } } return 0; }
还有个更加简单的做法:
#include<stdio.h> int main() { int a,b; int sum; while(scanf("%d%d\n",&a,&b) != EOF){ sum = a+b; if(sum < 0){ printf("-"); sum = -sum; } if(sum>=1000000){ printf("%d,%03d,%03d\n",sum/1000000, (sum/1000)%1000, sum%1000); } else if(sum >= 1000){ printf("%d,%03d\n",sum/1000,sum%1000); } else{ printf("%d\n", sum); } } return 0; }个人感觉有点取巧,但是解决的思路也很不错、精巧吧!