Dave's Brain

Browse - Programming Tips - How can I generate a random number in a range?

Date: 2014oct10
Language: C/C++

Q.  How can I generate a random number in a range?

A.  Call srand() once then rand() multiple times like this:

#include <time.h> #include <stdlib.h> #include <stdio.h> int randInRange(int min, int max) { return (rand() % (max - min + 1)) + min; } main() { srand(time(NULL)); for (int i = 0; i < 10; i++) { printf("%d\n", randInRange(10,100)); } }
Modern C++ has fancier random functions but this works everywhere.

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.