共計 676 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以使用 compareTo()
方法來比較 BigInteger
對象的大小。compareTo()
方法返回一個整數值,表示兩個 BigInteger
對象之間的大小關系。具體規則如下:
- 如果當前
BigInteger
對象小于指定的BigInteger
對象,則返回負整數。 - 如果當前
BigInteger
對象等于指定的BigInteger
對象,則返回 0。 - 如果當前
BigInteger
對象大于指定的BigInteger
對象,則返回正整數。
示例代碼如下:
import java.math.BigInteger;
public class Main {public static void main(String[] args) {BigInteger num1 = new BigInteger("1234567890123456789");
BigInteger num2 = new BigInteger("9876543210987654321");
// 比較大小
int result = num1.compareTo(num2);
if (result < 0) {System.out.println("num1 小于 num2");
} else if (result == 0) {System.out.println("num1 等于 num2");
} else {System.out.println("num1 大于 num2");
}
}
}
在上面的示例中,我們聲明了兩個 BigInteger
對象 num1
和num2
,然后使用 compareTo()
方法比較它們的大小,并根據比較結果輸出相應的信息。
丸趣 TV 網 – 提供最優質的資源集合!
正文完
發表至: Java
2024-04-13