-1

I want to generate a random number r in the loop, but I always get the same number N times. How can I achieve the desired effect? And because it's part of the algorithm, it needs to be fast while(r==i) Because I need a random number that's different than i

for (int i = 0; i < N; i++) 
{   
        srand(time(0));
        do {
            r = rand() % N;
        } while (r == i);
}

Even if the srand() function is outside the loop,after run N times,ris still the same

srand(time(0));
for (int i = 0; i < N; i++) 
{   
        
        do {
            r = rand() % N;
        } while (r == i);
}
leoshine
  • 1
  • 3
  • 1
    It seems as if your program runs the loop so fast that `time(0)` always returns the same value. And a pseudo random generator initilaized with the same value will produce the same next random value. – the busybee Jan 11 '22 at 13:14
  • I don't see why you are calling `srand` inside the `for` loop. Just call it once beforehand. – lurker Jan 11 '22 at 13:15
  • `while (r==i)` seems a slightly strange thing to test. "even with srand outside the loop" - which one? Can we get a [mre]? –  Jan 11 '22 at 13:27
  • 1
    Please show us a [mcve] with an example of desired output and actual output for `N` = 10. – Jabberwocky Jan 11 '22 at 14:06
  • I resolve the problom. Because out of the function, it has already use `srand(time(0))`. It was used twice, and when one was removed, the program worked as expected – leoshine Feb 04 '23 at 08:44

1 Answers1

1

It's somewhat unclear what you want, but this seems to do what you're looking for:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define N 100
int main(void)
{
  srand(time(0));
  for (int i = 0; i < N; i++) {
    int r;
    do {
      r = rand() % N;
    } while (r == i);

    printf("%d ", r);
  }
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115