Java实现给出四个随机值相加等于320,第1个数不小于80,不大于100,第2个数不小于80,不大于100,第3个数不小于60,不大于100,第4个数不小于60,不大于100
时间: 2024-04-29 20:25:08 浏览: 25
可以使用以下代码实现:
```java
import java.util.Random;
public class RandomSum {
public static void main(String[] args) {
int sum;
Random rand = new Random();
int num1, num2, num3, num4;
do {
num1 = rand.nextInt(21) + 80;
num2 = rand.nextInt(21) + 80;
num3 = rand.nextInt(41) + 60;
num4 = rand.nextInt(41) + 60;
sum = num1 + num2 + num3 + num4;
} while (sum != 320);
System.out.println("四个随机数分别为:" + num1 + " " + num2 + " " + num3 + " " + num4);
}
}
```
这个程序使用了一个 `do-while` 循环来生成四个随机数,并且保证它们相加等于320。其中,`rand.nextInt(n)` 会生成一个在0到n-1范围内的随机整数。
相关问题
Java实现给出四个随机值相加等于1000,第一个数不小于80,不大于100
可以使用以下代码实现:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
int num1 = rand.nextInt(21) + 80; // 80 <= num1 <= 100
int num2 = rand.nextInt(1001 - num1 - 3) + 1; // 1 <= num2 <= 1000 - num1 - 2
int num3 = rand.nextInt(1001 - num1 - num2 - 2) + 1; // 1 <= num3 <= 1000 - num1 - num2 - 1
int num4 = 1000 - num1 - num2 - num3; // num4 = 1000 - num1 - num2 - num3
System.out.println("四个随机值相加等于1000,第一个数不小于80,不大于100:");
System.out.println(num1 + " + " + num2 + " + " + num3 + " + " + num4 + " = 1000");
}
}
希望能帮到你。
Java实现给出四个随机值相加等于100,第一个数不小于30
可以使用如下代码实现:
```java
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
int num1 = rand.nextInt(71) + 30; // 生成30到100之间的随机数
int num2 = rand.nextInt(100 - num1 - 28) + 1; // 生成1到(100-num1-28)之间的随机数
int num3 = rand.nextInt(100 - num1 - num2 - 1) + 1; // 生成1到(100-num1-num2-1)之间的随机数
int num4 = 100 - num1 - num2 - num3; // 计算第四个数
System.out.println(num1 + " + " + num2 + " + " + num3 + " + " + num4 + " = 100");
}
}
```
这段代码会生成四个随机数,第一个数不小于30,且四个数相加等于100。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)