Arithmetic average
# Topic
The for-loop
# Problem
Arithmetic average
Write a program that reads two numbers aa and bb from the keyboard and calculates and outputs to the console the arithmetic average of all numbers from the interval [a; b][a;b], which are divisible by 33.
In the example below, the arithmetic average is calculated for the numbers on the interval [-5; 12][−5;12]. On this interval, there are 66 numbers divisible by 33, namely: -3, 0, 3, 6, 9, 12−3,0,3,6,9,12. Their arithmetic average equals 4.54.5.
The program input contains intervals, which always contain at least one number, which is divisible by 33.
Remember that the int type cannot contain fractions. Use a double variable to store the precise result of the division.
# Hint & Explain
// 输入提示
# Solution
# My solution
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// start coding here
int numberA = scanner.nextInt();
int numberB = scanner.nextInt();
int counter = 0;
double sum = 0.0;
for (int i = numberA; i <= numberB; i++) {
if (i % 3 == 0) {
counter++;
sum += i;
}
}
System.out.println(sum / counter);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Other solution 1
import java.util.Scanner;
import java.util.stream.IntStream;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double result = IntStream.rangeClosed(in.nextInt(), in.nextInt())
.filter(value -> value % 3 == 0)
.average()
.orElse(0);
System.out.println(result);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
编辑 (opens new window)
上次更新: 2023/04/14, 12:58:00