Random function

Hi everyone!

I need a random integer, but this integer must be lower than the number 10.
In this example it gives any random integer:

 
  n = rand();


I've tried to lower the RAND_MAX in the stdlib.h like this:
1
2
//#define RAND_MAX  0x7FFFU
#define RAND_MAX  0x000A 

But that isn't working either.

I Also tried this one:

 
   n = (rand() % 100);


And then the number is much lower, but not good enough. It must be lower than 10.

Can somebody help me??

Thank you.



n = rand() % 10
or
n = rand() * 10 / RAND_MAX;
The '%' operator returns the 'remaining' value: 30%4=2, because 30-4*n=2, where the value of 'n' is a round number (1,2,3..). This mains that when using a=b%c, 'a' will always be lower as 'c': you need n = rand()%10
If you want a "random" number, you should seed off of the time.
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <ctime> // to use the time function
#include <cstdlib>
using namespace std;

int main()
{
  srand(time(0));
  int n= rand % 10;
  cout << n;
}


This ought to work.
Topic archived. No new replies allowed.