1

Possible Duplicate:
How to generate a random number from within a range - C

How would you generate a random number between 1 and N-1 where N is a number the user punches in?

So far, my code is:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int number = 0; //number variable
    printf("This program will ask you for a number, an integer, and will print out a    random number from the range of your number 1, to N-1.");//output that explains the program's purpose and use to the user.
    //gets the input
    fgets(buffer, sizeof(buffer), stdin);
    sscanf(buffer, "%d", &number); //gets the input and stores it into variable number

    return (0);

}

Community
  • 1
  • 1
user1768884
  • 1,079
  • 1
  • 20
  • 34

4 Answers4

1

Here is the link to the referece for random.

http://www.cplusplus.com/reference/cstdlib/rand/

you can use

num= rand() % n + 1;

Luis Tellez
  • 2,785
  • 1
  • 20
  • 28
1

Depending on how "random" you want your numbers to be, you can use rand() function from the standard libc. This function will generate numbers between 0 and RAND_MAX. You can then get the result in the good range by using a modulo operation.

Note that this generator (a LCG) is neither suitable for cryptographic applications nor scientific applications.

If you want more suitable generators, have a look at generators such as Mersenne Twister (still not cryptosecure though).

jopasserat
  • 5,721
  • 4
  • 31
  • 50
Heis Spiter
  • 351
  • 3
  • 12
  • 1
    `NOT suitable for cryptographic applications nor scientific applications` From the looks of the question and context I don't think we have to worry about that. ;) – Mike Jan 18 '13 at 17:31
  • Sure, but that's just in case someone would use this answer for something else :-) – Heis Spiter Jan 18 '13 at 17:43
1

Try something like this:-

unsigned int
randomr(unsigned int min, unsigned int max)
{
       double x= (double)rand()/RAND_MAX;

       return (max - min +1)*x+ min;
}

Check out this link:- http://c-faq.com/lib/randrange.html

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

You need to look at rand. Bit of maths and you have a solution.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127