如何生成随机的5位数字取决于用户摘要 [英] How to generate random 5 digit number depend on user summary

查看:195
本文介绍了如何生成随机的5位数字取决于用户摘要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试生成5位数字为50的数字,具体取决于用户的总摘要.例如,用户给500000,然后我需要随机分配5位数乘50等于500000的数字

Hi guy i try to generate 50 number with 5 digit depend on user total summary. For example, User give 500000 and then i need to random number with 5 digit by 50 number equal 500000

我尝试这个,但是不是5位数字

i try this but it isn't 5 digit number

int balane = 500000;
            int nums = 50;
            int max = balane / nums;
            Random rand = new Random();
            int newNum = 0;
            int[] ar = new int[nums];
            for (int i = 0; i < nums - 1; i++)
            {
                newNum = rand.Next(0, max);
                ar[i] = newNum;
                balane -= newNum;
                max = balane / (nums - i - 1);

                ar[nums - 1] = balane;
            }

            int check = 0;
            foreach (int x in ar)
            {
                check += x;
            }

我已经尝试过,但是数组中的值只有我想得到的负值 正值

i tried already but value inside my array have negative value i want to get only positive value

请帮助我,如何解决此问题,并感谢您的进步.

Please help me, how to solve this and thank for advance.

推荐答案

我曾经在codereview.stackexchange.com上问过类似的问题.我已经修改了答案,以便为您生成一个五位数的序列.

I once asked a similar question on codereview.stackexchange.com. I have modified my answer to produce a five digit sequence for you.

此外,此代码足够快,可用于在单个请求中创建数以万计的代码.如果查看最初的问题和答案(链接到下面),您会发现它会在插入代码之前检查是否已使用该代码.因此,代码是唯一的.

Furthermore, this code is fast enough to be used to create tens of thousands of codes in a single request. If you look at the initial question and answer (linked to below) you will find that it checks to see whether the code has been used or not prior to inserting it. Thus, the codes are unique.

void Main()
{
    Console.WriteLine(GenerateCode(CodeLength));
}

private const int CodeLength = 10;
// since Random does not make any guarantees of thread-safety, use different Random instances per thread
private static readonly ThreadLocal<Random> _random = new ThreadLocal<Random>(() => new Random());

// Define other methods and classes here
private static string GenerateCode(int numberOfCharsToGenerate)
{
    char[] chars = "0123456789".ToCharArray();

    var sb = new StringBuilder();
    for (int i = 0; i < numberOfCharsToGenerate; i++)
    {
        int num = _random.Value.Next(0, chars.Length);
        sb.Append(chars[num]);
    }
    return sb.ToString();
}

原始问答: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆