Java 程序,在范围内生成随机数值,并获取最小和最大值
首先,创建一个 double 数组 −
double[] val = new double[10];
现在,生成并在循环中显示随机数,循环将持续到上述数组的长度。此处我们对随机数使用 nextInt −
for (int i = 0; i < val.length; i++) { val[i] = new Random().nextInt(100); System.out.println(val[i]); }
现在,获取最小值和最大值。将随机数组的每个值与最小值和最大值比较 −
double min = Double.MAX_VALUE; double max = Double.MIN_VALUE; for (int i = 0; i < val.length; i++) { if (val[i] < min) min = val[i]; if (val[i] > max) max = val[i]; }
示例
import java.util.Random; public class Demo { public static void main(String[] args) { double[] val = new double[10]; double min = Double.MAX_VALUE; double max = Double.MIN_VALUE; System.out.println("Random number array..."); for (int i = 0; i < val.length; i++) { val[i] = new Random().nextInt(100); System.out.println(val[i]); } for (int i = 0; i < val.length; i++) { if (val[i] < min) min = val[i]; if (val[i] > max) max = val[i]; } System.out.println("Minimum element = " + min); System.out.println("Maximum element = " + max); } }
输出
Random number array... 75.0 42.0 47.0 71.0 12.0 70.0 86.0 97.0 14.0 41.0 Minimum element = 12.0 Maximum element = 97.0
广告