2012-02-15 174 views
4

我在教自己CIL,到目前爲止一直行得通(昨天才真正開始),但我遇到了一個我無法弄清楚的問題。我提示用戶輸入一個int(int32),然後將其存儲並將其轉換爲浮點並顯示它。然而,無論我輸入什麼都會出現浮動。這裏是我的代碼:爲什麼將Int32轉換爲Float64會導致數據更改?

.assembly variables {} 
.method public static void main() cil managed 
{ 
    .entrypoint 
    .maxstack 8 
    .locals init (float64) 

    ldstr "Enter a digit: " 
    call void [mscorlib]System.Console::WriteLine(string) 
    call int32 [mscorlib]System.Console::Read() 
    conv.r8 
    stloc.0 
    ldstr "as a float: " 
    call void [mscorlib]System.Console::WriteLine(string) 
    ldloc.0 
    dup 
    call void [mscorlib]System.Console::Write(float64) 
    stloc.0 
    ldstr "Stored in location 0" 
    call void [mscorlib]System.Console::WriteLine(string) 
    ldloc.0 
    conv.i4 
    call void [mscorlib]System.Console::WriteLine(int32) 
    call int32 [mscorlib]System.Console::Read() // to pause before closing window 
    pop 
    ret 
} 

我只是用CIL鬼混,但想我會在我的整個清晰度例如扔。它編譯得很好,但是當我鍵入5時,它返回53作爲float和轉換後的int32。

有人可以請說明我做錯了什麼!


編輯:感謝Marc Gravell我能弄明白。對於那些有興趣誰,這裏是正確的代碼:

.assembly variables {} 
.method public static void main() cil managed 
{ 
    .entrypoint 
    .maxstack 8 
    .locals init (float64) 

    ldstr "Enter a digit: " 
    call void [mscorlib]System.Console::WriteLine(string) 
    call string [mscorlib]System.Console::ReadLine() 
    call int32 [mscorlib]System.Int32::Parse(string) 
    conv.r8 
    stloc.0 
    ldstr "as a float: " 
    call void [mscorlib]System.Console::WriteLine(string) 
    ldloc.0 
    dup 
    call void [mscorlib]System.Console::Write(float64) 
    stloc.0 
    ldstr "Stored in location 0" 
    call void [mscorlib]System.Console::WriteLine(string) 
    ldloc.0 
    conv.i4 
    call void [mscorlib]System.Console::WriteLine(int32) 
    call int32 [mscorlib]System.Console::Read() // to pause before closing window 
    pop 
    ret 
} 

回答

7

Console.Read返回一個Unicode碼點,或-1 EOF。 53是字符(非整數)'5'的代碼點。

你也許可以使用Console.ReadLineint.Parse

+0

太棒了!我很欣賞答案。我會在8分鐘內將其標記爲接受。非常感謝你 – Jetti 2012-02-15 20:54:38

+0

@Jetti新鮮的眼睛:p – 2012-02-15 20:57:29

+0

看起來我有更多的.NET學習。它在unicode中的事實從未跨過我的我:( – Jetti 2012-02-16 15:29:18

相關問題