2016-09-28 21 views
0

我是C#的新手,並在用戶輸入介於1和100之間的值的情況下進行一個小練習。(x)。計算機然後繼續生成一個隨機數,用於遊戲(y)併爲其自身生成另一個隨機數(z)比較x,y到z,看看哪一個更接近

該程序將x和z的值與y比較,以查看哪個值更接近y。 我在做比較的東西時遇到了一些麻煩。這是一個邏輯上的困難,而不是明智的編碼。我比較新,所以我非常憎恨命名約定。

class Roll 
{ 
    public int randomNumber { get; set; } //Random number for game 
    public int randomPc { get; set; } //Random number for pc 

    private void RandomGenerator() //Generates a number for int randomNumber and randomPc 
    { 
     Random rnd = new Random(); 
     randomNumber = rnd.Next(1, 100); 
     randomPc = rnd.Next(1, 100); 
    } 

    public Roll(int user) //Is where the comparison takes place 
    { 
     RandomGenerator(); 
     int compareUser; 
     int comparePc; 

     compareUser = user - randomNumber; 
     comparePc = randomPc - randomNumber; 


     if (compareUser < comparePc) 
      Console.WriteLine("\nPC won!\n{0} is closer to {1} than {2} is!", randomPc, randomNumber, user); 



     if (comparePc < compareUser) 
      Console.WriteLine("\nUser has won!\n{2} is closer to {1} than {0} is!", randomPc, randomNumber, user); 


    } 

} 

謝謝你的時間。

+0

你比較可能是負的。查看比較差異的*絕對值* –

+0

您將要爲您的值使用'Math.Abs​​'。 – Abion47

+0

作爲一個方面說明,你也錯過了玩家配合的情況('compareUser == comparePc') –

回答

0

您從未想過compareUser結果爲負的情況。因此,您需要在兩個數字之間計算the difference,如距離,而不僅僅是數學值user - randomNumber。我們使用Math.Abs()函數來做到這一點。

而且你的邏輯缺失的情況下進行compareUser是= comparePc

這是你的邏輯應該是這樣:

public Roll(int user) //Is where the comparison takes place 
{ 
    RandomGenerator(); 
    int compareUser; 
    int comparePc; 

    compareUser = Math.Abs(user - randomNumber); 
    comparePc = Math.Abs(randomPc - randomNumber); 


    if (compareUser < comparePc) 
     Console.WriteLine("\nPC won!\n{0} is closer to {1} than {2} is!", randomPc, randomNumber, user); 

    else if (comparePc < compareUser) 
     Console.WriteLine("\nUser has won!\n{2} is closer to {1} than {0} is!", randomPc, randomNumber, user); 
    else 
    { 
     // compareUser == comparePc - do something 
    } 

} 
相關問題