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);
}
}
謝謝你的時間。
你比較可能是負的。查看比較差異的*絕對值* –
您將要爲您的值使用'Math.Abs'。 – Abion47
作爲一個方面說明,你也錯過了玩家配合的情況('compareUser == comparePc') –