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;
                }
            }
  • 相关阅读:
    108. Convert Sorted Array to Binary Search Tree
    107. Binary Tree Level Order Traversal II
    106. Construct Binary Tree from Inorder and Postorder Traversal
    105. Construct Binary Tree from Preorder and Inorder Traversal
    104. Maximum Depth of Binary Tree
    103. Binary Tree Zigzag Level Order Traversal
    102. Binary Tree Level Order Traversal
    系统和进程相关信息
    文件I/0缓冲
    系统编程概念(文件系统mount等函数的使用)
  • 原文地址:https://www.cnblogs.com/LiYunQi/p/15678047.html
Copyright © 2011-2022 走看看