warwarwwqq 于 2015.06.01 09:15 提问

C#产生100个随机数，要求它们的和是100，请问怎么实现？要充分随机化。

C#产生100个随机数，要求它们的和是100，请问怎么实现？要充分随机化。

5个回答

caozhy      2015.06.01 09:33

warwarwwqq 写好了么？
2 年多之前 回复
warwarwwqq 采纳了，写给我吧
2 年多之前 回复
lakshyali   2015.06.01 10:19

Random ran=new Random();
int RandKey=ran.Next(0,99);
for(int i=0;i<100;i++){

int temp=ran.Next(0,100-RandKey);
}

warwarwwqq 不行
2 年多之前 回复
leation2shany   2015.06.01 12:21

private List Get100Numbers()
{
List rlts = new List();
double sum = 0;
for (int i = 0; i < 100; i++)
{
double number = this.GetRandomValue(i);
sum += number;
}
double rate = 100 / sum;
sum = 0;
for (int i = 0; i < rlts.Count; i++)
{
rlts[i] = rlts[i] * rate;
sum += rlts[i];
}
return rlts;
}

``````    private double GetRandomValue(int index)
{
Random r = new Random((int)DateTime.Now.Ticks + index);
double rlt = r.NextDouble() * 100;
return rlt;
}
``````
caozhy      2015.06.01 17:16

Random rnd = new Random();
var query = Enumerable.Range(0, 100).Select(x => rnd.NextDouble())ToArray();
var query = query.Select(x => x / query.Sum() * 100.0).ToArray();

caozhy      2015.06.01 17:17
`````` Random rnd = new Random();
var query = Enumerable.Range(0, 100).Select(x => rnd.NextDouble())ToArray();
query = query.Select(x => x / query.Sum() * 100.0).ToArray();
``````