c# 根据合计数,由随机函数生成加数

sniper_nie 2013-07-12 05:54:33

在图中,输入3000后,把第4个置0,然后由前3个生成。也有可能是将前3个置0,由第4个直接生成。每个数字都有指定范围,第4个的取值范围是2000-4000。
这样的写法如何实现?
...全文
162 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
devmiao 2013-07-12
  • 打赏
  • 举报
回复
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 . . .
Regan-lin 2013-07-12
  • 打赏
  • 举报
回复
没看明白你想问的是什么
sniper_nie 2013-07-12
  • 打赏
  • 举报
回复
如果有50个随机数的话,是不是用数组比较好?

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧