用Java语言完整写出:生成n个[0,1]之间的随机数(保留小数点后两位),计算随机数的和并输出; 生成n个[0,1]之间的随机数(保留小数点后两位),从大到小排序并输出; 生成n个[i, j]之间的随机数(保留小数点后两位),计算随机数的和并输出, 从大到小排序并输出; 其中i和 j从键盘输入。 生成n个[-1,1]之间的随机数(保留小数点后两位),要求所有随机数的和为1,并输出
时间: 2023-05-17 10:06:33 浏览: 272
以下是用Java语言完整写出的代码:
1. 生成n个[0,1]之间的随机数(保留小数点后两位),计算随机数的和并输出:
import java.util.Random;
public class RandomNumberGenerator {
public static void main(String[] args) {
int n = 10; // 生成10个随机数
double sum = 0.0;
Random random = new Random();
for (int i = 0; i < n; i++) {
double randomNumber = random.nextDouble();
sum += randomNumber;
System.out.printf("%.2f ", randomNumber);
}
System.out.printf("\nSum of random numbers: %.2f", sum);
}
}
2. 生成n个[0,1]之间的随机数(保留小数点后两位),从大到小排序并输出:
import java.util.Arrays;
import java.util.Random;
public class RandomNumberGenerator {
public static void main(String[] args) {
int n = 10; // 生成10个随机数
double[] randomNumbers = new double[n];
Random random = new Random();
for (int i = 0; i < n; i++) {
randomNumbers[i] = random.nextDouble();
}
Arrays.sort(randomNumbers);
for (int i = n - 1; i >= 0; i--) {
System.out.printf("%.2f ", randomNumbers[i]);
}
}
}
3. 生成n个[i, j]之间的随机数(保留小数点后两位),计算随机数的和并输出, 从大到小排序并输出;其中i和 j从键盘输入。
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class RandomNumberGenerator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter i: ");
double i = scanner.nextDouble();
System.out.print("Enter j: ");
double j = scanner.nextDouble();
int n = 10; // 生成10个随机数
double[] randomNumbers = new double[n];
double sum = 0.0;
Random random = new Random();
for (int k = 0; k < n; k++) {
double randomNumber = i + (j - i) * random.nextDouble();
randomNumbers[k] = randomNumber;
sum += randomNumber;
}
Arrays.sort(randomNumbers);
for (int k = n - 1; k >= 0; k--) {
System.out.printf("%.2f ", randomNumbers[k]);
}
System.out.printf("\nSum of random numbers: %.2f", sum);
}
}
4. 生成n个[-1,1]之间的随机数(保留小数点后两位),要求所有随机数的和为1,并输出:
import java.util.Random;
public class RandomNumberGenerator {
public static void main(String[] args) {
int n = 10; // 生成10个随机数
double[] randomNumbers = new double[n];
double sum = 0.0;
Random random = new Random();
for (int i = 0; i < n; i++) {
double randomNumber = -1.0 + 2.0 * random.nextDouble();
randomNumbers[i] = randomNumber;
sum += randomNumber;
}
for (int i = 0; i < n; i++) {
randomNumbers[i] /= sum;
System.out.printf("%.2f ", randomNumbers[i]);
}
}
}
阅读全文