search

Home  >  Q&A  >  body text

c++ - 循环中无法生成不同的随机数

for(i=0;i<h;i++)
{    
srand(time(0));
    b[i]=rand()%3;
        }
    在这个循环中b[i]不变 怎样才能让它变化?
怪我咯怪我咯2772 days ago396

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 15:19:23

    b[i] must not change in the loop, because you will initialize PRNG every time you loop.
    srand(time(0)); should be placed outside the loop.

    reply
    0
  • 阿神

    阿神2017-04-17 15:19:23

    srand(time(0));
    for(i=0;i<h;i++)
    {    
        b[i]=rand()%3;
    }

    reply
    0
  • Cancelreply