gpt4 book ai didi

c# - 让两个变量之一随机具有两个选项之一的更简单方法?

转载 作者:太空宇宙 更新时间:2023-11-03 21:50:01 25 4
gpt4 key购买 nike

我有两个变量,xy。其中之一应该具有从 0721 - this.Width 的随机 int 值。另一个必须是值 0721 - 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)。

关于c# - 让两个变量之一随机具有两个选项之一的更简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15034528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com