我目前正在处理生成随机数(1-20)并计算每个数字随机生成的次数。在textBox1
中,我选择了要生成的数字量。我在多行textBox2
中显示最终结果。我遇到的问题是,每次我再次单击该按钮时,它会重置随机生成数字的次数。
有没有我可以点击按钮x次并计算一个数字随机生成的次数而不重置计数?我特意在数组的帮助下尝试这个。
代码
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Random r = new Random();
private void button1_Click(object sender, EventArgs e)
{
var n = int.Parse(this.textBox1.Text);
var y =
Enumerable
.Range(0, n)
.Select(x => r.Next(20) + 1)
.ToArray();
var sum = y.Sum();
var avg = (double)sum / (double)n;
var frequency = y.ToLookup(x => x);
textBox2.Text = String.Join(Environment.NewLine, new[]
{
"Number of times an integer was randomly generated",
String.Format("{0} {1}", sum, avg),
}.Concat(Enumerable
.Range(1, 20)
.Select(x => String.Format("{0} ({1})", x, frequency[x].Count()))));
}
}
答案 0 :(得分:3)
变量的范围仅存在于button1_Click
方法中。您需要将其作为私有类变量移出,以便在点击之间保持它。它需要对您的代码进行一些小的重构才能实现。
public partial class Form1 : Form
{
private Random r = new Random();
private int[] counts = new int[20];
private static string newLine = Environment.NewLine;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int n = 0;
if (int.TryParse(this.textBox1.Text, out n))
{
// Clear the box
this.textBox2.Text = string.Empty;
var generatedList = new int[n];
for (int i = 0; i < n; i++)
{
// Upper bound is EXCLUSIVE
var gen = r.Next(1, 21);
counts[gen - 1]++;
generatedList[i] = gen;
}
this.textBox2.Text += PrintNumbers(generatedList);
this.textBox2.Text += PrintCounts(this.counts);
}
else
{
this.textBox2.Text = "Invalid input! Cannot generate numbers.";
}
}
private static string PrintNumbers(int[] numbers)
{
if (numbers == null)
{
return "No numbers generated" + newLine;
}
string result = "Generated sequence: {";
for (int i = 0; i < numbers.Length; i++)
{
result += numbers[i];
if (i < numbers.Length - 1)
{
result += ", ";
}
}
return result + "}" + newLine;
}
private static string PrintCounts(int[] counts)
{
if (counts == null)
{
return string.Empty;
}
string result = string.Empty;
for (int i = 0; i < counts.Length; i++)
{
result += "Number " + (i + 1) + " generated " + counts[i] + " times." + newLine;
}
return result;
}
}
请注意rand.next(min,max)
方法的上限是独占的,所以这意味着为了生成1到20之间的数字,你需要将它传递给1到21.不确定为什么会出现不一致 - 它是有点混乱。
n = 10
的输出Generated sequence: {12, 5, 12, 15, 8, 20, 6, 5, 16, 6}
Number 1 generated 0 times.
Number 2 generated 0 times.
Number 3 generated 0 times.
Number 4 generated 0 times.
Number 5 generated 2 times.
Number 6 generated 2 times.
Number 7 generated 0 times.
Number 8 generated 1 times.
Number 9 generated 0 times.
Number 10 generated 0 times.
Number 11 generated 0 times.
Number 12 generated 2 times.
Number 13 generated 0 times.
Number 14 generated 0 times.
Number 15 generated 1 times.
Number 16 generated 1 times.
Number 17 generated 0 times.
Number 18 generated 0 times.
Number 19 generated 0 times.
Number 20 generated 1 times.
答案 1 :(得分:1)
您需要记住实例字段中的一些数据。要么是先前在列表中生成的所有数字(这会引入很少的代码更改),要么将直方图本身生成为Dictionary<int, int>
。
当局部变量丢失时,实例字段会在调用事件处理程序时保留。