zoukankan      html  css  js  c++  java
  • PAT 1001 Format

    problem

    1001 A+B Format (20)(20 point(s))
    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
    

    anwser

    #include <iostream> 
    int main(){
    	int a, b;
    	int c;
    	int end[10];
    	std::cin>>a>>b;
    	c = a+b;
    	if (c==0) {
    		std::cout<<"0";
    		return 0;
    	}
    	if (c<0) {
    		std::cout<<"-";
    		c = -c;
    	}
    	int index = 0;
    	while(c>0){
    		end[index++] = c%1000;
    		c/=1000;
    	}
      	for(int i = index - 1; i >= 0; i--){
    	  	if(i != index-1){
    		  	if(end[i] == 0) 
    		  		std::cout<<"000";
    		    if(end[i] > 99)
    		    	std::cout<<end[i];
    		    else if(end[i] > 9){
    		    	std::cout<<"0";
    		    	std::cout<<end[i];
    		    }
    		    else if (end[i] > 0){
    		    	std::cout<<"00";
    		    	std::cout<<end[i];
    			}
    		}
    		else 
    			std::cout<<end[i]; 
    	    if (i != 0)
    	      std::cout<<",";
    	}
    	return 0;
    }
    

    experience

    • 边界条件要注意的
      • c ==0
    • 除首个数字外 end[i] == 0 的情况,并且要分类讨论
    • 首个数字不需要特殊处理
  • 相关阅读:
    Git log、diff、config 进阶
    Firefox 修改User Agent
    改Chrome的User Agent,移动版网络
    ThinkPHP 更新数据 save方法
    ThinkPHP:create()方法有什么用呢?
    js控制select选中显示不同表单内容
    GPS通讯协议协议(NMEA0183)
    Linux pkg-config命令
    OpenCV编程
    GTK编程
  • 原文地址:https://www.cnblogs.com/yoyo-sincerely/p/9250864.html
Copyright © 2011-2022 走看看