我正在用C#制作一个Windows窗体应用程序,我有一个for循环,它打印了20个元素,其中包含一个0到500之间的随机数。使用这些数字,我需要计算下一个数字。我想使用变量“numbers[i]”来打印它,但这不起作用,程序选择了新的随机数。下面是一些代码:
private void Form1_Load(object sender, EventArgs e)
{
CultureInfo ci = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = ci;
Thread.CurrentThread.CurrentCulture = ci;
int[] numbers = new int[numberOfItems];
Random random = new Random();
double total = 0;
var text = "";
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = random.Next(501);
beforeLoop.Text += $"Element {i} = {numbers[i]} \n";
total += numbers[i];
}
}
private void compare_Click(object sender, EventArgs e)
{
int count = 0;
count++;
if (count ==1 ) // knop is maar 1 keer drukbaar
{
compare.Enabled = false;
}
int[] numbers = new int[numberOfItems];
Random random = new Random();
double total = 0;
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = random.Next(501);
int numberBigger = numbers[i] + 10;
int numberSmaller = numbers[i] - 5;
total += numbers[i];
int number = int.Parse(numberBox.Text);
if (number > numbers[i])
{
printLabel.Text += $"Element {i} = {numberBigger}\n";
}
else
{
printLabel.Text += $"Element {i} = {numberSmaller}\n";
}
}
1条答案
按热度按时间w6mmgewl1#
每次创建一个新阵列:
int[] numbers = new int[numberOfItems];
但是numbers
应该在应用的整个生命周期中保持不变。