2016-04-14 86 views
-2
 int y = 0; 
     Console.WriteLine("insert x"); 
     int x = Console.Read(); 
     Console.WriteLine("insert n"); 
     int n = Console.Read(); 
     Console.WriteLine("insert a"); 
     int a = Console.Read(); 
     int sum = (2 * n - 1) * a; 
     int sum2 = (2 * n * a); 
     int sum3 = (2 * n + 1) * a; 
     if (x <= 0) y = 0; 
     else if (x > sum && x <= sum2) y = a; 
     else if (x > sum2 && x <= sum3 || n <= 3 || n >= 1) y = 0; 
     Console.WriteLine("Y = " + y); 
     Console.ReadLine(); 

    } 

無法插入所有值。在我插入xy打印和控制檯關閉後,我的錯誤是什麼?Console.Read()無法正常工作

回答

0

你應該使用輸入行並將其轉換爲int添加錯誤處理32個

帖是正確的代碼:

 int y = 0; 
     Console.WriteLine("insert x"); 
     int x = Convert.ToInt32(Console.ReadLine()); 
     Console.WriteLine("insert n"); 
     int n = Convert.ToInt32(Console.ReadLine()); 
     Console.WriteLine("insert a"); 
     int a = Convert.ToInt32(Console.ReadLine()); 
     int sum = (2 * n - 1) * a; 
     int sum2 = (2 * n * a); 
     int sum3 = (2 * n + 1) * a; 
     if (x <= 0) y = 0; 
     else if (x > sum && x <= sum2) y = a; 
     else if (x > sum2 && x <= sum3 || n <= 3 || n >= 1) y = 0; 
     Console.WriteLine("Y = " + y); 
     Console.ReadLine(); 
+1

謝謝我使用此代碼。 – Zeroone

+0

然後接受答案。 – 2016-04-14 12:09:09

+1

不知道如何接受 – Zeroone

2

而不是Read使用ReadLine。只有這樣,你可以肯定在用戶實際按下ENTER全線返回 - 直到用戶按下ENTER,但後來只返回一個字符的ASCII碼Read塊。如果您閱讀documentation示例,則會變得清晰。

在您的例子,如果你輸入「1」,然後按ENTER,以Read接下來調用實際上將返回的ASCII碼爲1\r\n

要明確:Read返回進入,但是你輸入的字符的ASCII 代碼,讓你在使用它錯了 - 你需要做的是轉換字符串什麼用戶進入到一個號碼,像這樣:

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

你也可以檢查錯誤很容易像這樣:

int number; 
if (!Int32.TryParse(Console.ReadLine(), out number)) 
{ 
    Console.WriteLine("What you entered is not a number!"); 
    return; 
} 
+0

當我使用ReadLine我得到錯誤cuz我不​​能隱式地將類型'字符串'轉換爲'int' – Zeroone

+0

是的。當然你有,而且你應該。我會編輯我的答案。 –

1

Console.Read只顯示下一個字符。這不是你想要的。什麼情況是這樣的:

  • 鍵入7 =>你讀的字符(ASCII代碼)0x37x
  • ENTER =>你讀0x0A\r)爲n 等...

要使用Console.ReadLine()終止,當你打ENTER並返回string,你可以解析爲int

Console.Write("Insert x: "); 
string input = Console.ReadLine(); 
int x = int.Parse(input); 

您可能希望如果用戶輸入「ABC」,而不是一個int或使用

int x; 
if (!int.TryParse(input, out x)) 
    Console.WriteLine("This was no number!"); 
0

每個人都給出瞭解決方案,但之所以爲 您的代碼不起作用是這樣的。

的 Console.Read

返回的keyPressed的ASCII值。 它的意思就是把像

int i = Console.Read(); 

,打鍵盤上的4key將存儲值53,這是我,而不是預期的烏爾整數「4」的4key的變量的ASCII值。

要通過Console.Read查看變量a,n和y中真實存儲的內容後使用斷點來完全理解此檢查變量值。