Loading

PAT-A 1001

https://pintia.cn/problem-sets/994805342720868352/problems/994805528788582400

C语言

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            int a = in.nextInt();
            int b = in.nextInt();
            int result = a + b;
            
            if(result < 0) {
                result = -result;
                System.out.print("-");
            }
            
            if(result < 1000) {
                System.out.println(result);
            }
            else if(result < 1000000) {
                System.out.println(result/1000 + "," + result%1000);
            } else {
                System.out.println(result/1000000 + "," + (result/1000)%1000 + "," + result%1000);
            }
            
        }
    }
}

Java

第一次总是有几个测试点过不去,发现是因为 1,003 被输出成了 1,3
需要加入格式化输出命令

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            int a = in.nextInt();
            int b = in.nextInt();
            int result = a + b;
            if(result < 0) {
                result = -result;
                System.out.printf("-");
            }
            if(result < 1000) {
                System.out.printf("%d%n", result);
            }
            else if(result < 1000000) {
                System.out.printf(("%d,%03d%n"), result/1000, result%1000);
            } else {
                System.out.printf(("%d,%03d,%03d%n"), result/1000000, (result/1000)%1000, result%1000);
            }
        }
    }
}
posted @ 2021-09-09 21:31  ljs9  阅读(24)  评论(0)    收藏  举报