Java Random Numbers: Generate and Sum
In Java, you can use the Math.random() method to generate random numbers, and use a loop to add up these random numbers, and finally calculate the sum. Here is an example code:
public class RandomSum {
public static void main(String[] args) {
int n = 10; // 产生的随机数个数
double sum = 0; // 总和
for (int i = 0; i < n; i++) {
double randomNum = Math.random();
sum += randomNum;
System.out.println("随机数" + (i + 1) + ": " + randomNum);
}
System.out.println("总和: " + sum);
}
}
In this example, we generate 10 random numbers and add them together into the sum variable. Finally, we output these random numbers and their total sum. You can modify the number and range of random numbers as needed.