运行 我的随机数程序时屏幕为空
empty screen while running my random numbers program
我想编写一个生成彼此不同的随机数的基本程序,但是当我 运行 该程序时,我总是看到一个空白屏幕。我认为有一个逻辑错误,我检查了它们彼此不相似的数字,然后卡在 "for" 循环中。你能检查我的代码吗?谢谢..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace denemeTahtasi2
{
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[7];
Random random = new Random();
for (int i = 0; i < numbers.Length; i++)
{
c:
numbers[i] = random.Next(1, 50);
for (int j = 0; j < numbers.Length; j++)
{
if (numbers[i] == numbers[j])
{
goto c;
}
}
}
foreach (var item in numbers)
{
Console.Write(item + " ");
}
Console.ReadLine();
}
}
}
注意:是的,我知道我可以使用 .contains 方法来做到这一点,但我想弄清楚这个程序有什么问题。
问题是你有一个无限循环。 i
和 j
都从 0
开始,所以当您执行 if (numbers[i] == numbers[j])
时,它总是 return true
因为您正在查看相同的指数。然后你点击 goto
语句并重新做一遍。
要解决此问题,请添加一个 if
条件以在 i
和 j
是相同索引时跳过比较:
for (int i = 0; i < numbers.Length; i++)
{
c:
numbers[i] = random.Next(1, 50);
for (int j = 0; j < numbers.Length; j++)
{
// If i and j are the same index, skip the comparison
if (i == j) continue;
if (numbers[i] == numbers[j])
{
goto c;
}
}
}
此外,由于我们不需要在 索引 i
之后查看任何数字 ,我们可以通过将 j
限制为小于 i
的数字。这样,我们就不再需要比较了,因为 j
总是小于 i
:
for (int i = 0; i < numbers.Length; i++)
{
c:
numbers[i] = random.Next(1, 50);
// Only compare indexes that are before this one
// (since we haven't set any after this one yet)
for (int j = 0; j < i; j++)
{
if (numbers[i] == numbers[j])
{
goto c;
}
}
}
我想编写一个生成彼此不同的随机数的基本程序,但是当我 运行 该程序时,我总是看到一个空白屏幕。我认为有一个逻辑错误,我检查了它们彼此不相似的数字,然后卡在 "for" 循环中。你能检查我的代码吗?谢谢..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace denemeTahtasi2
{
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[7];
Random random = new Random();
for (int i = 0; i < numbers.Length; i++)
{
c:
numbers[i] = random.Next(1, 50);
for (int j = 0; j < numbers.Length; j++)
{
if (numbers[i] == numbers[j])
{
goto c;
}
}
}
foreach (var item in numbers)
{
Console.Write(item + " ");
}
Console.ReadLine();
}
}
}
注意:是的,我知道我可以使用 .contains 方法来做到这一点,但我想弄清楚这个程序有什么问题。
问题是你有一个无限循环。 i
和 j
都从 0
开始,所以当您执行 if (numbers[i] == numbers[j])
时,它总是 return true
因为您正在查看相同的指数。然后你点击 goto
语句并重新做一遍。
要解决此问题,请添加一个 if
条件以在 i
和 j
是相同索引时跳过比较:
for (int i = 0; i < numbers.Length; i++)
{
c:
numbers[i] = random.Next(1, 50);
for (int j = 0; j < numbers.Length; j++)
{
// If i and j are the same index, skip the comparison
if (i == j) continue;
if (numbers[i] == numbers[j])
{
goto c;
}
}
}
此外,由于我们不需要在 索引 i
之后查看任何数字 ,我们可以通过将 j
限制为小于 i
的数字。这样,我们就不再需要比较了,因为 j
总是小于 i
:
for (int i = 0; i < numbers.Length; i++)
{
c:
numbers[i] = random.Next(1, 50);
// Only compare indexes that are before this one
// (since we haven't set any after this one yet)
for (int j = 0; j < i; j++)
{
if (numbers[i] == numbers[j])
{
goto c;
}
}
}