0

I am trying to find random numbers from 1 to 5. I made this code-

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

int main(){
  int r;

  r = rand() % 5 + 1;
  printf("%d ", r);
    
  
  switch (r){
    case 1:
      printf("1\n");
      break;
    case 2:
      printf("2\n");
      break;
    case 3:
      printf("3\n");
      break;
    case 4:
      printf("4\n");
      break;
    case 5:
      printf("5\n");
      break;
  }
  return 0;
}

For some reason, for both outputs, for the first print, and the switch, I just get the output "4 4." How do I get it so that each time it's a different number in that list? Do I need to loop it?

Jacob G
  • 31
  • 3
  • 3
    Why would you expect the outputs to be different? – dbush Oct 06 '21 at 03:51
  • 2
    Does this answer your question? [Why do I get the same result with rand() every time I compile and run?](https://stackoverflow.com/questions/1783629/why-do-i-get-the-same-result-with-rand-every-time-i-compile-and-run) – JASLP doesn't support the IES Oct 06 '21 at 03:56
  • 1
    If you want multiple random numbers, you need to call `rand` multiple times. – dbush Oct 06 '21 at 03:56
  • You have to seed the random number generator by calling `srand()` with a suitable value. Ideally, the seed should itself be random. Be careful and [only call `srand()` once](https://stackoverflow.com/q/7343833/15168), though. – Jonathan Leffler Oct 06 '21 at 04:13

0 Answers0