标题:随机获取数值
只看楼主
lijunwsp
Rank: 1
等 级:新手上路
帖 子:48
专家分:0
注 册:2007-2-8
结帖率:100%
 问题点数:0 回复次数:1 
随机获取数值
有这样一个题目,求大家帮助解答下,谢谢
给任意几位数,有可能是5位、6位、7位数,位数是不定的,如果是5位,就是12345,6位就是123456,依此类推,看这些数有多种种组合,从这些组合中随机抽出10位数,是随机的
例如:给的是5位数,我现在只能让他生成所有不同的组合,遇到的问题是:
1.我不知道如何随机抽取10个数
2.如果是6位数那我又得写个6个潜逃循环,太麻烦了
希望大家给个优化一些的算法,谢谢
private void butMake_Click(object sender, EventArgs e)
{
 int i1, i2, i3, i4,i5;
 int sum;
 string str = string.Empty;

            sum = 0;
            txtresult.Text = "";

            for (i1 = 1; i1 < 6; i1++)
            {
                for (i2 = 1; i2 < 6; i2++)
                {
                    for (i3 = 1; i3 < 6; i3++)
                    {
                        for (i4 = 1; i4 < 6; i4++)
                        {
                            for (i5 = 1; i5 < 6; i5++)
                            {
                                sum = sum + 1;
                                str = str + i1.ToString() + i2.ToString() + i3.ToString() + i4.ToString() + i5.ToString() = "\r\n";
                            }
                        }
                    }
                }
            }

            lblnum.Text = sum.ToString();
            txtresult.text = str;
}
搜索更多相关主题的帖子: 数值 随机 位数 sum int 
2008-07-11 09:20
bygg
Rank: 16Rank: 16Rank: 16Rank: 16
来 自:乖乖的心中
等 级:版主
威 望:241
帖 子:13555
专家分:3076
注 册:2006-10-23
得分:0 
/// <summary>
        /// 获取指定位数的数字字符串
        /// </summary>
        /// <param name="strLen">字符串的长度</param>
        /// <returns></returns>
        private string getRandomStr(int strLen)
        {
            string retStr = "";

            if (strLen < 10)
            {
                Random r = new Random();
                string subStr = string.Empty;
                for (int i = 0; i < strLen; i++)
                {
                    subStr = r.Next(0, 9).ToString();    //获得随机数(0到9之间)
                    while (true)
                    {
                        if (retStr.IndexOf(subStr) == -1)    //不存在相同数字
                        {
                            retStr += subStr;
                            break;
                        }
                        else    //存在相同数字,重新取值
                        {
                            subStr = r.Next(0, 9).ToString();
                        }
                    }
                }
            }

            return retStr;
        }

这个方法是获取一个没有重复数字的字符串. 希望对你有帮助.

飘过~~
2008-07-11 10:24



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-223453-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.267894 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved