通过数组c ++随机递增

问题描述 投票:-3回答:1

我正在努力理解使用'rand()'从一个整数数组中随机读取数字的概念。我在1-3之间创建了一个随机数生成器,想要输出一个数组的索引,然后让生成器从前一个索引中随机输出下一个生成的数字,直到它到达数组的末尾。例如:

  1. 'rand()'= 3,'array [2]'
  2. 'rand()'= 2,'array [4]'
  3. 'rand()'= 3,'array [7]'

如果这有道理?等等

我目前使用的代码只输出一系列随机数。我放置了一个“种子”,所以我可以查看相同的序列。

int main() 
{ 
 int arrayTest[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 
 17, 18, 19, 20};   
 srand(4);
 for(int i = 0; i < 20; i++)  
    {  
     arrayTest[i] = (rand() % 3);
     cout << arrayTest[i] << endl;
    }




}
c++ arrays indexing srand
1个回答
1
投票

我有点猜测你真正想要的东西。但它似乎想要对索引进行随机增量,并使用该索引在循环中从数组中读取。

所以这段代码不会像你想要的那样做

 arrayTest[i] = (rand() % 3);

它使用顺序(即非随机)索引将随机值写入(而不是读取)到数组。

这就是我想你想要的

int main() 
{ 
    int arrayTest[20] = { ... };   
    srand(4);
    int index = -1;
    for(int i = 0; i < 20; i++)  
    {  
         index += (rand() % 3) + 1; // add random number from 1 to 3 to index
         if (index >= 20) // if index too big for array
             index -= 20; // wrap around to beginning of array
         cout << arrayTest[index] << endl; // read array at random index, and output
    }
}

但我不完全确定,特别是你的testArray的数字顺序为1到20的方式让我有点怀疑。也许如果你解释为什么你想做任何你想做的事情,它会更清楚一点。

© www.soinside.com 2019 - 2024. All rights reserved.