c# 根据合计数,由随机函数生成加数
在图中,输入3000后,把第4个置0,然后由前3个生成。也有可能是将前3个置0,由第4个直接生成。每个数字都有指定范围,第4个的取值范围是2000-4000。
这样的写法如何实现?
c# 随机函数 --------------------编程问答-------------------- 如果有50个随机数的话,是不是用数组比较好? --------------------编程问答-------------------- 没看明白你想问的是什么 --------------------编程问答--------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int total = 3000;
int minrange4 = 2000;
int maxrange4 = 4000;
int count = 3;
List<int> result = foo(total, minrange4, maxrange4, count);
foreach (var item in result)
Console.WriteLine(item);
}
static List<int> foo(int total, int minrange4, int maxrange4, int count)
{
Random rnd = new Random();
int r4 = rnd.Next(minrange4 > total ? total - count : minrange4,
maxrange4 < total ? maxrange4 : total - count);
var list = new List<int>();
while (list.Count() != count - 1)
{
int r = rnd.Next(0, total - r4 - list.Sum() - count + list.Count());
list.Add(r);
}
list.Add(total - list.Sum() - r4);
list.Add(r4);
return list;
}
}
}
527
115
241
2117
Press any key to continue . . .
270
21
67
2642
Press any key to continue . . .
补充:.NET技术 , C#