生成等長隨機數值的方法


需要根據輸入字符串,生成一個等長的隨機數值,網上查了一下,沒發現比較直接的方法。

自己寫了一個,為便於理解,加了一些中間過程的變量。

雖然可以實現目的,但覺得有些繁瑣,執行效率也不好,故貼於此,請高手指教。

 

       /// <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;
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM