pat甲级 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).

计算a+b并以一种格式输出,将和的每三位用一个逗号隔开,除非和小于4位

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner =new Scanner(System.in);
        String []a = scanner.nextLine().split(" ");
        int sum = Integer.parseInt(a[0])+Integer.parseInt(a[1]);


        if(sum<0){
            sum = Math.abs(sum);
            System.out.print("-");//打印负号
        }
        if(sum<1000)
        {
            System.out.print(sum);
        }
        else if(sum>=1000&&sum<1000000){
            System.out.printf("%d,%03d",sum/1000,sum%1000);//使用c预制的函数,%03d表示最少输出三位。不够的在右边用0填充
        }
        else if(sum>=1000000){

            System.out.printf("%d,%03d,%03d",sum/1000000,sum/1000%1000,sum%1000);
        }
    }
}

 

posted @ 2021-04-03 15:42  chenyuan#  阅读(38)  评论(0编辑  收藏  举报