c# float和double的“坑”

來源:互聯網
上載者:User

標籤:style   class   blog   code   http   color   

定義一個float類型的變數=0.7,結果在IL中卻是0.69999999。

乘以10之後,擷取整數值。得到的卻是6。通過查看IL,竟然被轉換成double類型再轉換。就變成6了。

Demo:

IL:

.method private hidebysig static void  Main(string[] args) cil managed{  .entrypoint  // 代碼大小       93 (0x5d)  .maxstack  2  //定義變數  .locals init ([0] float32 val,           [1] int32 i)  IL_0000:  nop  IL_0001:  ldc.r4     0.69999999  //將0.69999999賦值給第0個變數。明明定義的是0.7  IL_0006:  stloc.0  IL_0007:  ldc.i4.s   10  /將10賦值給第一個變數  IL_0009:  stloc.1  //double類型的0.7  IL_000a:  ldc.r8     0.69999999999999996  IL_0013:  ldloc.1  IL_0014:  conv.r8  IL_0015:  mul  IL_0016:  call       float64 [mscorlib]System.Math::Floor(float64)  IL_001b:  call       void [mscorlib]System.Console::WriteLine(float64)  IL_0020:  nop  IL_0021:  ldloc.0  IL_0022:  call       void [mscorlib]System.Console::WriteLine(float32)  IL_0027:  nop  //從堆棧中載入出val  IL_0028:  ldloc.0  //從堆棧中載入出i  IL_0029:  ldloc.1  //將i轉換為float類型  IL_002a:  conv.r4  //val*i  IL_002b:  mul  //將乘法運算之後的結果轉換為double類型  IL_002c:  conv.r8  //調用Math.Floor對運算後的結果處理  IL_002d:  call       float64 [mscorlib]System.Math::Floor(float64)  IL_0032:  call       void [mscorlib]System.Console::WriteLine(float64)  IL_0037:  nop  IL_0038:  ldloc.0  IL_0039:  conv.r8  IL_003a:  call       void [mscorlib]System.Console::WriteLine(float64)  IL_003f:  nop  IL_0040:  ldloc.0  IL_0041:  ldloc.1  IL_0042:  conv.r4  IL_0043:  mul  IL_0044:  conv.r8  IL_0045:  call       void [mscorlib]System.Console::WriteLine(float64)  IL_004a:  nop  IL_004b:  ldloc.0  IL_004c:  conv.r8  IL_004d:  ldloc.1  IL_004e:  conv.r8  IL_004f:  mul  IL_0050:  call       void [mscorlib]System.Console::WriteLine(float64)  IL_0055:  nop  IL_0056:  call       string [mscorlib]System.Console::ReadLine()  IL_005b:  pop  IL_005c:  ret} // end of method Program::Main
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.