随机数生成器(C#)

#####生成范围内随机数并保留小数#####

1、代码

1 private void FormGenrtRandom_Load(object sender, EventArgs e) 2 { 3 //默认保留小数点后两位 4 comboBoxDecimalReserve.SelectedIndex = 2; 5 } 6 7 private void buttonConfirm_Click(object sender, EventArgs e) 8 { 9 //清空 10 textBoxResult.Clear(); 11 exeWhenBtnClicked(); 12 } 13 14 private void exeWhenBtnClicked() 15 { 16 //随机数左区间 17 //随机数右区间 18 //生成数量 19 int startNum = Convert.ToInt32(textBoxStartNum.Text); 20 int endNum = Convert.ToInt32(textBoxEndNum.Text); 21 int countNum = Convert.ToInt32(textBoxCountNum.Text); 22 23 //小数保留位数 24 int selectedIndex = comboBoxDecimalReserve.SelectedIndex; 25 int decimalPlace = selectedIndex; 26 //储存随机数数组 27 double[] res = new double[countNum]; 28 29 Random random = new Random(); 30 for (int i = 0; i < countNum; i++) 31 { 32 //设置时间间隔 33 //使每次循环的随机数种子不同 34 Thread.Sleep(1); 35 double randNum = random.NextDouble() * (endNum - startNum) + startNum; 36 //保留小数位数 37 res[i] = Math.Round(randNum, decimalPlace); 38 } 39 40 for (int i = 0; i < countNum; i++) 41 { 42 //结果输出 43 textBoxResult.Text = textBoxResult.Text
                        + res[i].ToString()
                        + Environment.NewLine; 44 } 45 46 47 }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwwjgw.html