1

I would like to generate random numbers between 1 and 25 with the method rand().
But I only know how to generate random numbers this way, which includes the number zero by default:

int r = rand() % 26 /* random int between 0 and 25 */

Anyone? Thank you.

Julia
  • 509
  • 1
  • 7
  • 19

1 Answers1

4

Very simple

int r = 1 + rand() % 25 /* random int between 1 and 25 */

but you should use this

int r = (int)(1.0 + 25.0 * rand() / RAND_MAX)

as mentioned in the comments, the second is the more robust way to generate random numbers see this link

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97