[英]Cast int to double then back to int in java
快速提問。
這總是真的嗎?
int i = ...;
double d = i;
if (i == (int) d) ...
還是我需要四舍五入才能確定?
if (i == Math.round(d)) ...
是的,所有可能的int
值都可以安全地往返到double
。
您可以使用以下代碼驗證它:
for (int i = Integer.MIN_VALUE; ; i++) {
double d = i;
if (i != (int) d) {
throw new IllegalStateException("i can't be converted to double and back: " + i);
}
if (i == Integer.MAX_VALUE) {
break;
}
}
請注意,我沒有使用普通for
循環,因為它會跳過Integer.MAX_VALUE
或無限循環。
請注意,對於int
/ float
或long
/ double
,情況並非如此!
如果您使用的是慢速計算機或沒有時間運行循環來檢查自己,Java 語言規范的相關部分在此處§ 5.1.2 擴大轉換:
以下 19 種基本類型的特定轉換稱為擴展基本類型轉換:
- 字節到 short、int、long、float 或 double
- 短到 int、long、float 或 double
- char 到 int、long、float 或 double
- int 到 long、float 或 double
- 長時間浮動或加倍
- 浮動加倍
擴大原始轉換不會丟失有關數值整體大小的信息。 實際上,從整數類型擴大到另一種整數類型以及從 float 到 double 的轉換根本不會丟失任何信息。 數值被完全保留。 [...]
(下一節§ 5.1.3 Narrowing Primitive Conversions確保返回的方式 double -> int 也不會丟失任何信息。)
Joachim 解決方案的變體。
int i=Integer.MIN_VALUE;
do {
if(i != (int)(double) i) throw new AssertionError(i + " != (int)(double) "+i);
} while(i++ < Integer.MAX_VALUE);
找到導致轉換為浮點數時出錯的最小值。
int i = 0;
do {
if(i != (int)(float) i) throw new AssertionError(i + " != (int)(float) "+i);
} while(i++ < Integer.MAX_VALUE);
印刷
java.lang.AssertionError: 16777217 != (int)(float) 16777217
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.