2014-07-05 119 views
-3

我需要編寫一個'猜數字'程序,包括1-100之間的數字,包括一個While循環。它還需要告訴用戶他們到底有多少猜測,坦率地說我不知道​​該怎麼做。另外,用戶在程序響應之前必須輸入他們的猜測3次,並告訴他們它是高於還是低於隨機數。 這裏是我的代碼:猜數字C#遊戲

Random RandomClass = new Random(); 
int x = RandomClass.Next(1, 100); 
Console.WriteLine("I am thinking of a number between 1-100. Can you guess what it is?"); 
int guess = 0; 
while (guess != x) 
{ 
    guess = Convert.ToInt32(Console.ReadLine()); // ReadLine 1 
    if (guess == x) 
    { 
    Console.WriteLine("Well done! The answer was " + x + " and you found it in XXXX guesses"); 
    Console.ReadLine(); // ReadLine 2 
    } 
    else if (guess != x) 
    { 
    if (guess < x) 
    { 
     Console.WriteLine("No, the number I am thinking of is higher than " + guess + ". Can you guess what it is?"); 
     Console.ReadLine(); // ReadLine 3 
    } 
    else if (guess > x) 
    { 
     Console.WriteLine("No, the number I am thinking of is lower than " + guess + ". Can you guess what it is?"); 
     Console.ReadLine(); // ReadLine 4 
    } 
    } 
    Console.ReadLine(); // ReadLine 5. 
} 

下面是什麼樣子時,我喜歡調試:

I am thinking of a number between 1-100. Can you guess what it is? 
50 
50 
50 
No, the number I am thinking of is lower than 50. Can you guess what it is? 
40 
40 
40 
No, the number I am thinking of is higher than 40. Can you guess what it is? 
45 
45 
45 

等。

+3

好吧增加每圈一個變量,你必須'到Console.ReadLine()'四次,你只需要一次。沒有冒犯,但這個問題對於Stack Overflow來說實在太基本了。你只是錯過了一個計數器... – Kobi

+1

我不知道爲什麼你還沒有試圖調試你的代碼,看看所有的多個輸入請求來自哪裏。如果您沒有使用Visual Studio,請考慮安裝一個(即[Visual Studio Express for Desktop](http://www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx))和調試代碼在那裏 - 你應該看到@Kobi建議當你「跳過」每一行時,它會在同一次迭代中多次等待輸入。 –

+0

@Kobi我刪除了所有的'Console.ReadLine()',除了頂部的那個,但在程序響應之前我仍然需要輸入兩次我的猜測。另外,什麼是櫃檯? – musiclover

回答

1

我冒昧地在您的ReadLine調用中提供數字,同時改進問題的格式,所以讓我們看看上面輸出中的第二個條目。與40一個進入了三次。三個輸入對應於Readline()來電4,5,1.

只有ReadLine()調用1實際上獲取任何數據,其他應該被刪除。

對於嘗試次數,你應該添加在環路

// --- Snip --- 
int guess = 0; 
int guessCount = 0; 
while (guess != x) 
{ 
    guessCount++; // Increase guessCount with one for each turn of the loop. 
    guess = Convert.ToInt32(Console.ReadLine()); // ReadLine 1 
// --- Snip ----