2015-09-05 58 views
-2

我最近開始學習C#,所以我試圖做一些簡單的事情,但不能使程序成爲100%的功能。我在Visual Studio中做了它,並給出了每個值,答案在相同C#中的第一個控制檯應用程序#

大於0

using System; 

namespace ConsoleApplication1 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     Console.WriteLine("Please enter a number"); 
     int userinput = Console.Read(); 
     if (userinput > 0) Console.Write("Bigger than 0"); 
      else if (userinput < 0) Console.Write("Less than 0"); 
        else Console.Write("Equal to 0"); 
     Console.Write("\nPress <ENTER> to exit\n"); 
     Console.ReadKey(); 

     } 

} 
} 

回答

0

越大Console.Read()方法讀按壓,而不是在控制檯輸入的整數值的密鑰的代碼。你必須使用Console.ReadLine()閱讀完整的字符串,並將其轉換爲整數,如:

int userinput = Convert.ToInt32(Console.ReadLine()); 

注意,如果輸入的字符串會不會是一個恰當的整數,該程序將失敗。您可以考慮使用Int32.TryParse()並處理無效輸入。

+0

我現在明白了,謝謝。 –

+0

正確,但如果用戶輸入無法轉換爲整數的內容,則解決問題的方式會導致其他問題。請建議使用Int32.TryParse – Steve

+0

@Steve是的,當然會。但是,對於基本學習IMO來說,這很好。無論如何,將更新我的答案。 –

相關問題