![](/img/trans.png)
[英]How to Generate one random number more than other random numbers in an array?
[英]Generate 4 random number whose sum is 100 and one is more than 50
我需要创建4个总和为100的int随机数。其中一个大于50,并且大于其他整数。 我有这个:
int a=0, b=0,c=0,d=0;
int cem=100;
while (a+b+c+d=cem){
Random perc = new Random();
a = perc.Next(50, 100);
b = perc.Next(0, 50);
c = perc.Next(0, 50);
d = perc.Next(0, 50);
}
在编译器中我得到2错误:
分配的左侧必须是变量,索引器的属性无法将类型'int'隐式转换为'bool'
更换
while (a+b+c+d=cem){
与
while (a+b+c+d!=cem){
您正在使用赋值( =
)而不是比较( ==
/ !=
)。
除了关于编译器错误消息的其他答案之外,您还应该移动该行
Random perc = new Random();
到while
循环的外部。 您只需要一个随机数生成器,由于时间种子,在快速循环中重新生成它可能会产生相同的结果。
如果您考虑一下,四个随机数之和为100意味着它们中只有三个是随机数,而第四个是100减去其他三个数...因此,与其做循环,不如先生成一个数字,然后再生成一个带有其余数的数字间隔,然后是第三个。
为什么要使用循环? 祝你好运:-)
(浪费了太多的CPU)
这就是我要开始做的事情;
class Program
{
static void Main(string[] args)
{
int a = 0, b = 0, c = 0, d = 0;
int cem = 100;
Random perc = new Random();
a = perc.Next(50, cem);
cem -= a;
b = perc.Next(0, cem);
cem -= b;
c = perc.Next(0, cem);
cem -= c;
d = cem;
Console.WriteLine("{0} + {1} + {2} + {3} = {4}",a,b,c,d,a+b+c+d);
Console.ReadKey(false);
}
}
The left-hand side of an assignment must be a variable
Cannot implicitly convert type 'int' to 'bool'
while需要==,假设C#像C。==是相等测试,=是赋值。
(很明显,这是为什么会导致第一条错误消息的原因。您可能需要考虑为什么它会解释第二条错误消息,但是由于这样做是一个很好的练习,因此我将不作解释。)
这样的事情怎么样,循环次数会减少吗?
int a = 0, b = 0, c = 0, d = 0;
int cem = 100;
Random perc = new Random();
a = perc.Next(50, cem);
b = perc.Next(0, cem - a);
c = perc.Next(0, cem - a - b);
d = cem - a - b - c;
class Program {
void Main() {
var random = new Random();
// note it says one of them is more than 50
// so the min value should be 51 not 50
var a = random.Next(51, 100);
// the rest of the number will be less than `a`
// because `a` is more than 50 so the max `remaining`
// will be is 49 (100 - 51)
var remaining = 100 - a;
var b = random.Next(0, remaining);
remaining -= b;
var c = random.Next(0, remaining);
remaining -= c;
var d = remaining;
Console.WriteLine("a: " + a);
Console.WriteLine("b: " + b);
Console.WriteLine("c: " + c);
Console.WriteLine("d: " + d);
Console.WriteLine("total: " + (a + b + c + d));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.