我有两个变量,x 和 y。其中之一应该具有从 0 到 721 - this.Width 的随机 int 值。另一个必须是值 0 或 721 - this.Width。我已经设法创建了它,但是这么长的代码对于这么小的东西来说似乎很愚蠢。可能这是唯一(或最佳)解决方案,但我想确定一下,是否有更短的方法?
这是我的代码:
Random random = new Random();
int x, y;
if (random.Next(2) == 1)
{
x = random.Next(721 - this.Width);
if (random.Next(2) == 1)
{
y = 721 - this.Height;
}
else
{
y = 0;
}
}
else
{
y = random.Next(721 - this.Height);
if (random.Next(2) == 1)
{
x = 721 - this.Width;
}
else
{
x = 0;
}
}
请您参考如下方法:
你可以这样写:
Random random = new Random();
int a = random.Next(2) * (721 - this.Width);
int b = random.Next(721 - this.Width);
int c = random.Next(2) * (721 - this.Height);
int d = random.Next(721 - this.Height);
int x, y;
Boolean t = (random.Next(2) == 1);
x = (t) ? a : b;
y = (t) ? d : c;
请注意,如果您发现更长的版本更容易理解,则此代码并不比您的更好。编写代码没有正确的方法,可理解性通常比简洁更有值(value)。
