2011-03-26 23 views
-1

我是新:爲什麼2會自動轉換爲299?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     private static void Main() 
     { 
      Console.WriteLine("Welcome to my calculator"); 
      Console.WriteLine("Calculator only supports -,+,/,*"); 
      Console.WriteLine("Calculator V1.20 alpha"); 

      Console.WriteLine("Enter your first number"); 
      int num1 = Console.ReadKey().KeyChar; 
      Console.WriteLine("Enter your operator"); 
      Console.WriteLine(); 
      char operation = Console.ReadKey().KeyChar; 
      Console.WriteLine("Enter your second number"); 
      Console.WriteLine(); 
      int num2 = Console.ReadKey().KeyChar; 
      //the answer variables 
      int answersubtract = num1 - num2; 
      int answeradd = num1 + num2; 
      int answermulti = num1 * num2; 
      int answerdiv = num1/num2; 


      if (operation == '-') 
      { 
       Console.WriteLine(answersubtract); 
      } 

      else if (operation == '+') 
      { 
       Console.WriteLine(answeradd); 
      } 
      else 
      { 
       if (operation == '*') 
       { 
        Console.WriteLine(answermulti); 
       } 

       else 
       { 
        if (operation == '/') 
        { 
         Console.WriteLine(answerdiv); 

        } 
       } 
      } 

      Console.ReadKey(); 
     } 
    } 
} 

編輯

我發送到程序的輸入是:

1 + 2

+0

你能告訴我們你有什麼問題嗎? 「當我做_a_,_b_發生,但我想_c_」 – 2011-03-26 00:28:51

+2

你可能會更具體一點?在什麼情況下將'2'轉換爲'299'? – David 2011-03-26 00:29:24

回答

3
int num1 = Console.ReadKey().KeyChar; 

您正在閱讀的是字符,而不是數字。查看ConsoleKeyInfo.KeyChar的文檔。

允許用戶輸入實數:對錯誤處理

int num1 = int.Parse(Console.ReadLine()); 

焦點,並在你的程序的第2版的開關聲明。

+0

謝謝你挑選你的 – unknown 2011-03-26 00:37:09

+0

@John - 我不會用十英尺的杆子去碰那個。無論如何,這並不相關。 – 2011-03-26 00:53:16

+0

299在哪裏發揮作用(而不是229)? – 2011-03-26 00:56:47

0

因爲當你輸入2它表示爲char其val你是229

+0

你是怎麼輸入的+ – unknown 2011-03-26 00:29:15

+1

除了''2''的ASCII值是'0x32'或十進制50. – 2011-03-26 00:30:15

+1

@約翰:這個答案確實確定了一個合理的問題,我認爲它不值得贊成。 – 2011-03-26 00:32:02

相關問題