Per*_*her 0 c# arrays random numbers
我创建了一个程序,用户可以在其中选择有多少数字的数组,这个数组应该有随机值.嗯,事实并非如此.要在每次尝试为每个数组参数签名后检查,我会使console.writeline显示随机分配的编号.最后整个数组由最后一个randomed这个方法填充:
static void Main(string[] args)
{
Console.WriteLine("Set the number of arguments in mineArray:");
string argumentsNumber = Console.ReadLine();
int argumentsNumberInt = Convert.ToInt32(argumentsNumber);
int[] mineArray = new int[argumentsNumberInt];
Random rand = new Random();
//set up values to each index of array
foreach (int i in mineArray)
{
mineArray[] = rand.Next(1, 10);
Console.WriteLine(i + " " + mineArray[i]);
}
string a = "asd";
foreach (int k in mineArray)
{
if (mineArray[k] % 3 == 0 || mineArray[k] % 5 == 0)
{
if (mineArray[k] % 3 == 0 && mineArray[k] % 5 == 0)
{
a = "Able to divide by 3 and 5";
}
else
{
if (mineArray[k] % 3 == 0) { a = "Able to divide only by 3"; }
if (mineArray[k] % 5 == 0) { a = "Able to divide only by 5"; }
}
}
else
{
a = "Number unable to divide";
}
Console.WriteLine(mineArray[k] + " " + a);
}
Run Code Online (Sandbox Code Playgroud)
我假设你这样做mineArray[i] = rand.Next(1, 10);,否则这将无法编译(你的代码遗漏了i).
问题出在你的foreach循环中:
int[] mineArray = new int[argumentsNumberInt];
Random rand = new Random();
//set up values to each index of array
foreach (int i in mineArray)
Run Code Online (Sandbox Code Playgroud)
foreach每次分配随机变量时,这将通过一个填充零的数组运行mineArray [0].
用途for:
for (int i = 0; i < argumentsNumberInt; i++)
Run Code Online (Sandbox Code Playgroud)