我是C#的新手并进行了一项小练习,用户输入1到100之间的值(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)
您从未想过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
}
}