帮我写一段代码,要求 用java实现随机生成保留两位小数的数字
时间: 2024-05-05 11:14:55 浏览: 152
Sure, here's some Java code that generates a random number with two decimal places:
```
import java.util.Random;
public class RandomNumberGenerator {
public static void main(String[] args) {
// Create new Random object
Random rand = new Random();
// Generate random number with two decimal places
double num = rand.nextDouble() * 100;
num = Math.round(num * 100.0) / 100.0;
// Print out result
System.out.println("Random number with two decimal places: " + num);
}
}
```
This code uses the `Random` class in Java to generate a random number between 0 and 1. It then multiplies this number by 100 to get a number between 0 and 100, and rounds it to two decimal places using the `Math.round()` function.
阅读全文