当前位置:编程学习 > C/C++ >>

PAT-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
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
 
#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;  
}  

 

 
补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,