簡體   English   中英

.NET與Mono:從2 ^ 32轉換為int的不同結果

[英].NET vs Mono: different results for conversion from 2^32 as double to int

TL; DR為什么(int)Math.Pow(2,32)在Mono上返回0 ,而在.NET上返回Int32.MinValue


在Mono上測試.NET編寫的代碼時,我偶然發現以下行:

var i = X / ( (int)Math.Pow(2,32) ); 那條線當然沒有多大意義,我已經將它更改為long

但是我很好奇為什么我的代碼沒有在.NET上拋出DivideByZeroException ,所以我檢查了Mono和.NET上該表達式的返回值

誰能解釋一下結果?

恕我直言,這個問題是學術性的; 該文檔僅承諾“結果是目標類型的未指定值” ,因此每個平台都可以自由地執行其所需的任何操作。

投射可能溢出的結果時應格外小心。 如果有這種可能性,並且獲得特定結果而不是給定平台提供的任何任意實現很重要,則應使用checked關鍵字並捕獲可能發生的任何OverflowException ,以所需的任何顯式行為對其進行處理。

“結果是目標類型的未指定值”。 我認為查看.NET實現中實際發生的事情會很有趣。

這與IL中的OpCodes.Conv_I4字段有關: " Conversion from floating-point numbers to integer values truncates the number toward zero. When converting from a float64 to a float32, precision can be lost. If value is too large to fit in a float32 (F), positive infinity (if value is positive) or negative infinity (if value is negative) is returned. If overflow occurs converting one integer type to another, the high order bits are truncated" 會將 " Conversion from floating-point numbers to integer values truncates the number toward zero. When converting from a float64 to a float32, precision can be lost. If value is too large to fit in a float32 (F), positive infinity (if value is positive) or negative infinity (if value is negative) is returned. If overflow occurs converting one integer type to another, the high order bits are truncated"它再次表示溢出是未指定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM