如何输出两个在固定范围的随机数
时间: 2024-10-18 07:03:17 浏览: 22
在大多数编程语言中,包括Python、Java和C#等,你可以使用内置的随机数生成函数来获取指定范围内的随机数。以下是几个常见语言的例子:
1. **Python** (使用`random`模块):
```python
import random
def generate_random_numbers(start, end):
return random.randint(start, end), random.randint(start, end)
start = 0
end = 100
num1, num2 = generate_random_numbers(start, end)
print(f"Random numbers between {start} and {end}: {num1}, {num2}")
```
2. **Java** (使用`java.util.Random`类):
```java
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
int start = 0;
int end = 100;
int num1 = rand.nextInt((end - start) + 1) + start;
int num2 = rand.nextInt((end - start) + 1) + start;
System.out.println("Random numbers between " + start + " and " + end + ": " + num1 + ", " + num2);
}
}
```
3. **C#** (使用`System.Random`类):
```csharp
using System;
class Program {
static void Main() {
Random rand = new Random();
int start = 0;
int end = 100;
int num1 = rand.Next(start, end + 1);
int num2 = rand.Next(start, end + 1);
Console.WriteLine($"Random numbers between {start} and {end}: {num1}, {num2}");
}
}
```
在上述代码中,`rand.nextInt(end - start + 1)`会生成一个[0, `end - start`)的随机整数,然后加`start`确保得到的是指定范围内的值。
阅读全文