需要将大于输入数字的所有数字相加。种子就是这样,以便可以复制输出。
示例:
[12,16,45,3,32]
输入值:30
输出:
77
import java.util.*;
public class SumAbove {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int seed = scnr.nextInt();
Random rand = new Random(seed);
System.out.println("Enter a positive integer between 1-100 to search above:");
int minVal = scnr.nextInt();
int[] arr = new int[rand.nextInt(100)+1];
for (int i=0; i<arr.length; i++) {
arr[i] = rand.nextInt(100)+1;
}
System.out.println(Arrays.toString(arr));
int sum = 0;
for (int i=0; i<arr.length; i++) {
if (arr[i]>minVal) {
sum += i;
}
}
System.out.println(sum);
}
}
答案 0 :(得分:2)
您不需要sum += i;
(如前所述),而只需要一个循环(因为您知道第一个循环之前的最小值),而不是sum += arr[i];
。喜欢,
int minVal = scnr.nextInt(), sum = 0;
int[] arr = new int[rand.nextInt(100) + 1];
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt(100) + 1;
if (arr[i] > minVal) {
sum += arr[i];
}
}
System.out.println(Arrays.toString(arr));
System.out.println(sum);
答案 1 :(得分:1)
将sum += i
替换为sum += arr[i]
。
变量i
只是位置。 arr[i]
是该位置的值。
答案 2 :(得分:0)
public static void main(String[] args) {
int nums[] = { 12, 16, 45, 3, 32 };
int value;
int sum = 0;
System.out.println("Enter a positive integer between 1-100 to search above: ");
Scanner sc = new Scanner(System.in);
value = sc.nextInt();
for (int i = 0; i < nums.length; i++) {
if (nums[i] > value)
sum = nums[i] + sum;
}
System.out.println(sum);
}
答案 3 :(得分:0)
这是在Java 8+中使用流实现的方法。
int nValues = 5;
int minValue = 1;
int maxValue = 30;
Random r = new Random();
for (int i = 0; i < 10; i++) {
int[] values = r.ints(nValues, minValue, maxValue + 1).toArray();
// min to sum is the threshold
int minToSum = r.nextInt(7) + 10; // between 10 an 16 inclusive
int sum = Arrays.stream(values).filter(m -> m > minToSum).sum();
System.out.println("sum = " + sum + " for greater than " + minToSum
+ " : " + Arrays.toString(values));
}
以下输出。
sum = 65 for values greater than 11 : [2, 10, 14, 23, 28]
sum = 92 for values greater than 10 : [13, 18, 15, 19, 27]
sum = 94 for values greater than 12 : [25, 6, 14, 25, 30]
sum = 54 for values greater than 10 : [14, 8, 14, 26, 5]
sum = 22 for values greater than 15 : [15, 8, 13, 22, 14]
sum = 28 for values greater than 13 : [3, 28, 9, 6, 5]
sum = 87 for values greater than 13 : [5, 18, 25, 21, 23]
sum = 31 for values greater than 13 : [16, 7, 12, 2, 15]
sum = 42 for values greater than 15 : [7, 22, 20, 10, 5]
sum = 40 for values greater than 12 : [2, 2, 13, 27, 9]