随机数发生器 - 可变长度 [英] Random number generator - variable length

查看:97
本文介绍了随机数发生器 - 可变长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我的程序(见下文)生成长度为8-12个字符的随机字符串(由数字组成)。

Currently my program (see below) generates random strings (made of numbers) from 8 - 12 characters in length.

public static string GenerateNewCode(int CodeLength)
{
    string newCode = String.Empty;
    int seed = unchecked(DateTime.Now.Ticks.GetHashCode());
    Random random = new Random(seed);

    // keep going until we find a unique code       `
    do
    {
        newCode = random.Next(Convert.ToInt32(Math.Pow(10, CodeLength - 1)), Convert.ToInt32(Math.Pow(10, CodeLength) - 1)).ToString("0000");
    }
    while (!ConsumerCode.isUnique(newCode));

    // return
    return newCode;
}

然而,当<$ c $时,他们的方法存在问题c> codeLength 为10或更大会导致错误,因为10 9 大于 int32.MaxValue

However, their is a problem with the method, when the codeLength is 10 or greater it causes error because 109 is greater than int32.MaxValue.

不确定如何解决这个问题。

Not sure how to get around this issue.

推荐答案

你的代码在做同样的事情没有一些怪胎:

Your code doing the same thing without some freak lines:

public static string GenerateNewCode(int CodeLength)
{
    Random random = new Random();
    StringBuilder output = new StringBuilder();

    do
    {   
        for (int i = 0; i < CodeLength; i++)
        {
            output.Append(random.Next(0, 10));
        }
    }
    while (!ConsumerCode.isUnique(output.ToString()));
    return output.ToString();
}

这篇关于随机数发生器 - 可变长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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