Java使用random类随机定义一个有5个数据的double类型的数组,使用循环和判断语句找出数组中的最大值和最小值并打印输出
时间: 2024-06-04 13:10:25 浏览: 11
你好,很高兴为您回答问题。
以下是解答:
double[] array = new double[5];
Random random = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = random.nextDouble();
}
double max = array[0];
double min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
} else if (array[i] < min) {
min = array[i];
}
}
System.out.println("最大值:" + max);
System.out.println("最小值:" + min);
希望能够帮助到您!
相关问题
Java使用random类随机定义一个10个数据的int型数组,实现将所有的偶数放在前半部分,将所有的奇数放在数组后半部分
可以使用两个指针,一个指向数组的开头,一个指向数组的末尾。然后遍历数组,如果当前元素是偶数,就将其放在开头指针的位置,并将开头指针向后移动一位;如果当前元素是奇数,就将其放在末尾指针的位置,并将末尾指针向前移动一位。最后,所有的偶数就都在前半部分,所有的奇数就都在后半部分了。以下是实现的示例代码:
int[] arr = new int[10];
Random rand = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt(100);
}
int start = 0;
int end = arr.length - 1;
while (start < end) {
if (arr[start] % 2 == 0) {
start++;
} else if (arr[end] % 2 != 0) {
end--;
} else {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
用java定义一个有10个元素的三位数随机整型数组,找出最大最小值
以下是Java代码示例:
```java
import java.util.Random;
public class Main {
public static void main(String[] args) {
int[] arr = new int[10];
Random rand = new Random();
// 填充数组
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt(900) + 100; // 生成 100~999 的随机整数
}
// 初始化最大值和最小值
int max = arr[0];
int min = arr[0];
// 查找最大值和最小值
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
// 输出结果
System.out.println("数组元素为:");
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println("\n最大值为:" + max);
System.out.println("最小值为:" + min);
}
}
```
以上代码使用 `Random` 类生成 10 个随机的三位数整数,并查找其中的最大值和最小值。运行结果如下:
```
数组元素为:
720 262 294 312 533 245 459 254 528 621
最大值为:720
最小值为:245
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)