问题遇到的现象和发生背景
我要对一个随机生成的浮点数数组进行操作,能够运行但是结果是错误的。
用代码块功能插入代码,请勿粘贴截图
package lab2;
import java.util.Random;
import java.util.Scanner;
public class Part1 {
public static double readSize(String message) {
//output the greeting to make clear to the user what's happening
System.out.print(message);
Scanner scanner = new Scanner(System.in);
double size = scanner.nextDouble();
return size;
}
public static void printArray(double[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void fillArrayByRandom(double[] array) {
Random random = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = random.nextDouble(20);
}
}
public static void fillArrayByUser(double[] array) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < array.length; i++) {
System.out.print("Enter the " + (i + 1) + " element of " +
array.length);
array[i] = scanner.nextDouble();
}
}
public static void main(String[] args) {
//read the size of the vector (linear array)
double size = readSize("Count of elements: ");
double[] array = new double[(int) size];
fillArrayByRandom(array);
System.out.println("Array:");
printArray(array);
System.out.println();
//we need to count zero elements.
//计数数组中零元素的个数
double amount = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == 0) {
amount = amount + array[i]*0 + 1;
}
}
System.out.println("The number of zero elements is = " + amount);
//we need to find the index of min value in the array
//to do that we will save value for the "current minimal value"
//(current means that for the current i value)
double min = array[0];
//and minIndex - because we must find the sum before the min element
//it is the way to store it's position
double minIndex = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
minIndex = i;
}
}
//sum of elements after the min value
//求最小元素之后的元素和
double sum = 0;
for (int i = 0; i > minIndex; i++) {
sum = array[i];
}
//print the result
System.out.println("The sum after the minimal elements is " + sum);
//将数组按照递增顺序重新排列
for (int i = 0; i < array.length / 2; i++) {
double tmp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = tmp;
}
System.out.println("Reversed array:");
for (int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
}
}
运行结果及报错内容
Count of elements: 5
Array:
5.416085002789357 9.13728160490736 16.674225755360524 6.5628141875893125 18.38307664064794
The number of zero elements is = 0.0
The sum after the minimal elements is 0.0
Reversed array:
18.38307664064794 6.5628141875893125 16.674225755360524 9.13728160490736 5.416085002789357
我想要达到的结果
我已经在代码中标注了操作在的位置,麻烦帮忙看一下怎么改
1.计数随机生成的浮点数数组中零元素的个数
2.对最小元素之后的元素进行求和
3.将数组按照递增顺序重新排列