Question #6698   Submitted by Answiki on 09/21/2022 at 11:18:20 AM UTC

In C, how to pick a random number between 0 and 100 inclusive?

Answer   Submitted by Answiki on 09/21/2022 at 11:20:52 AM UTC

In C, the rand() function allows to generate a pseudo-random number. The following code allows to restrict the draw between 0 and 100 inclusive.

x = rand()%101;  

The generic formula is detailed here. Bellow is the complete code that initializes the pseudorandom generator to avoid always drawing the same numbers:

#include <stdio.h>  // For printf
#include <stdlib.h> // For rand() srand() 
#include <time.h>   // For time()

int main(void) {  

  // Initialize the pseudo random generator
  // Without this line, we would always pick the same number
  srand(time(NULL));

  // Generate a random number between 0 and 100 (included)
  int x = rand()%101;  

  // Display the number
  printf("Random number : %d\n", x );
    
  return 0;
}




5 events in history
Answer by Answiki on 09/21/2022 at 11:20:52 AM

In C, the rand() function allows to generate a pseudo-random number. The following code allows to restrict the draw between 0 and 100 inclusive.

x = rand()%101;  

The generic formula is detailed here. Bellow is the complete code that initializes the pseudorandom generator to avoid always drawing the same numbers:

#include <stdio.h>  // For printf
#include <stdlib.h> // For rand() srand() 
#include <time.h>   // For time()

int main(void) {  

  // Initialize the pseudo random generator
  // Without this line, we would always pick the same number
  srand(time(NULL));

  // Generate a random number between 0 and 100 (included)
  int x = rand()%101;  

  // Display the number
  printf("Random number : %d\n", x );
    
  return 0;
}




Question by Answiki 09/21/2022 at 11:18:25 AM
In C, how to pick a random number between 0 and 100 included?
Question by Answiki 09/21/2022 at 11:18:20 AM
In C, how to pick a random number between 0 and 100 inclusive?
Answer by Answiki on 09/21/2022 at 11:18:10 AM

In C, the rand() function allows to generate a pseudo-random number. The following code allows to restrict the draw between 0 and 100 inclusive.

x = rand()%101;  

The generic formula is detailed here. Bellow is the complete code that initializes the pseudorandom generator to avoid always drawing the same numbers:

#include <stdio.h>  // For printf
#include <stdlib.h> // For rand() srand() 
#include <time.h>   // For time()

int main(void) {  

  // Initialize the pseudo random generator
  // Without this line, we would always pick the same number
  srand(time(NULL));

  // Generate a random number between 0 and 100 (included)
  int x = rand()%101;  

  // Display the number
  printf("Random number : %d\n", x );
    
  return 0;
}




Question by Answiki 09/21/2022 at 11:11:55 AM
In C, how to pick a random number between 0 and 100?
# ID Query URL Count

Icons proudly provided by Friconix.