java double比较大小
时间: 2023-10-17 08:15:14 浏览: 85
test2_JavaDouble类型比较大小_java编程_
Java中比较两个double类型的大小可以使用Double.compare()方法或者直接使用比较运算符。
1. 使用Double.compare()方法
语法:
```java
public static int compare(double d1, double d2)
```
示例:
```java
double a = 3.14159;
double b = 2.71828;
int result = Double.compare(a, b);
if (result > 0) {
System.out.println(a + " is greater than " + b);
} else if (result < 0) {
System.out.println(a + " is less than " + b);
} else {
System.out.println(a + " is equal to " + b);
}
```
输出:
```
3.14159 is greater than 2.71828
```
2. 直接使用比较运算符
示例:
```java
double a = 3.14159;
double b = 2.71828;
if (a > b) {
System.out.println(a + " is greater than " + b);
} else if (a < b) {
System.out.println(a + " is less than " + b);
} else {
System.out.println(a + " is equal to " + b);
}
```
输出:
```
3.14159 is greater than 2.71828
```
注意:由于double类型的精度问题,使用直接比较运算符可能会出现意外的结果,建议使用Double.compare()方法。
阅读全文