Skip to content

L1-008 求整数段和

给定两个整数AB,输出从AB的所有整数以及这些数的和。

输入格式:

输入在一行中给出 2 个整数AB,其中 −100≤AB≤100,其间以空格分隔。

输出格式:

首先顺序输出从AB的所有整数,每 5 个数字占一行,每个数字占 5 个字符宽度,向右对齐。最后在一行中按Sum = X的格式输出全部数字的和X

输入样例:

tex
-3 8
-3 8

输出样例:

tex
-3   -2   -1    0    1
    2    3    4    5    6
    7    8
Sum = 30
-3   -2   -1    0    1
    2    3    4    5    6
    7    8
Sum = 30

Solution:

java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String[] input = in.readLine().split(" ");
        int a = Integer.parseInt(input[0]);
        int b = Integer.parseInt(input[1]);
        StringBuilder sb = new StringBuilder();
        int index = 0, sum = 0;

        for (int i = a; i <= b; i++) {
            index++;
            sum += i;
            sb.append(String.format("% 5d", i));
            if (index % 5 == 0 && i != b) sb.append("\n");
        }
        System.out.printf("%s\nSum = %d", sb, sum);
    }
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String[] input = in.readLine().split(" ");
        int a = Integer.parseInt(input[0]);
        int b = Integer.parseInt(input[1]);
        StringBuilder sb = new StringBuilder();
        int index = 0, sum = 0;

        for (int i = a; i <= b; i++) {
            index++;
            sum += i;
            sb.append(String.format("% 5d", i));
            if (index % 5 == 0 && i != b) sb.append("\n");
        }
        System.out.printf("%s\nSum = %d", sb, sum);
    }
}

Released under the MIT License.