2014-07-08 73 views
0

我创建的程序中,用户可以选择有多少个数字有数组,这个数组应该有随机值。那么,它不会。为了检查每次尝试对每个数组参数签名的次数,我使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); 
    } 
+1

什么'mineArray [] = rand.Next(1,10);'什么意思? –

+0

@AlexeiLevenkov相信他的意思是'mineArray [i] ...' –

+0

你应该使用正常的'for'循环来设置值,因为'foreach'只是一个只读函数 –

回答

5

我假设你做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) 

foreach将通过用零填充阵列运行,每次分配随机变量mineArray [0]

使用for

for (int i = 0; i < argumentsNumberInt; i++) 
+1

你们真不可思议。五分钟,我知道比猜测我弄乱了什么还多百倍。 :) – Perisher

+0

学习如何使用断点和[各种调试窗口](http://msdn.microsoft.com/en-us/library/esta7c62.aspx)可以派上用场。 :) – CodeCaster