Java实现给出四个随机值相加等于100,第一个数不小于30
时间: 2024-05-01 10:18:43 浏览: 19
可以使用如下代码实现:
```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。
相关问题
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
可以通过以下代码实现:
```java
import java.util.Random;
public class RandomSum {
public static void main(String[] args) {
Random random = new Random();
int a = random.nextInt(100);
int b = random.nextInt(100 - a);
int c = random.nextInt(100 - a - b);
int d = 100 - a - b - c;
System.out.println("随机数为:" + a + "," + b + "," + c + "," + d);
}
}
```
这段代码会生成四个随机数,相加等于100,并输出这四个数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)