zoukankan      html  css  js  c++  java
  • 生成等长随机数值的方法

    需要根据输入字符串,生成一个等长的随机数值,网上查了一下,没发现比较直接的方法。

    自己写了一个,为便于理解,加了一些中间过程的变量。

    虽然可以实现目的,但觉得有些繁琐,执行效率也不好,故贴于此,请高手指教。

           /// <summary>
            /// 数值字符串转换成等长的随机数
            /// </summary>
            /// <param name="inputStr">输入字符串</param>
            /// <returns></returns>
            private static string StringConvertRandomDouble(string inputStr)
            {
                if (inputStr.Length > 17)
                {
                    return inputStr;//Double类型超出17位长度,需用科学计数法表示。转换会抛出异常。
                }
                string top = "";
                int inputStrLenght;//输入字符串原始长度
                if (double.TryParse(inputStr, out double newDouble))//判断能否转换位double类型
                {
                    int IntegerLength;//整数部分长度
                    double tempDouble = Math.Floor(newDouble);//向下取整,可能有符号,下面判断处理
                    if (tempDouble < 0)
                    {
                        IntegerLength = tempDouble.ToString().Length - 1;
                        top = "-";
                        inputStrLenght = inputStr.Length - 1;
                    }
                    else
                    {
                        IntegerLength = tempDouble.ToString().Length;
                        inputStrLenght = inputStr.Length;
                    }
                    string a = "1".PadRight(IntegerLength, '0');//得到等长 100
                    string b = "9".PadLeft(IntegerLength, '9');//得到等长的 999
                    double minDouble = Convert.ToDouble(a);
                    double maxDouble = Convert.ToDouble(b);
                    Random _random = new Random();
                    double outputDouble;
                    if (_random != null)
                    {
                        //在指定的范围内取随机的 Double
                        outputDouble = _random.NextDouble() * (maxDouble - minDouble) + minDouble;
                    }
                    else
                    {
                        outputDouble = 0.0d;
                    }
                    return top + outputDouble.ToString().Substring(0, inputStrLenght);
                }
                else
                {
                    return inputStr;
                }
            }
  • 相关阅读:
    操作技巧——电脑远程控制
    软件安装——internal error2503/2502
    系统常识——虚拟内存地址
    操作技巧——保障无线上网的技巧
    操作技巧——输入法转换问题
    软件安装——彻底卸载MySQL
    Java——this
    python百度贴吧爬虫
    糗事百科python爬虫
    python请求带cookie
  • 原文地址:https://www.cnblogs.com/LiYunQi/p/15678047.html
Copyright © 2011-2022 走看看