• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 179
  • Last Modified:

How can i generate a random no within 100????

Hi !

                           I used rand()  fn to generate a random no.How can i define the max limit for that....there
                   is  RAND_MAX....but i want to override that....

                   Can anyone pls help.....

                   Thanks in advance.
1 Solution
You don't need to override the RAND_MAX, all you need to do is once you get a random number, you mod it with 100, you'll get integer between 0 and 99 (add 1 to get b/w 1 and 100) or mod 101 to get b/w 0 and 100

// assume you do all initialize stuff up here with srand already
x = rand();

random_number = x % 100; // this gives you integer, 0 <= random_number <= 99

If u want to increase the range of Random Numbers then u can use srand() function from Stdlib.h
or If u want to give ur own value then try opening stdlib.h and modify the value of RAND_MAX in it. Im not Very Sure of second thing Just Check it.
All the Best
Changing the value of RAND_MAX is a very bad idea.
Go with ecubhume's solution
Follow ecebhume's advice, wrap it in a small function:
  inline int
  random(int n)
    return rand() % n;
ceenaAuthor Commented:
Thanks all.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now