I want to know a small c code to generate random numbers.It could be within a certain range.
I want to know if rand() function will generate a random number

Recommended Answers

All 10 Replies

there's no such thing as a random number.

num = rand();

will return a "pseudo-random" number over the interval between 0 and 2^32, depending on your compiler.

not truly random, but i suspect that it will have enough "appearance" of being random for your purposes.

I want to know a small c code to generate random numbers.It could be within a certain range.
I want to know if rand() function will generate a random number

Yes, rand() will generate a random number. Also, look up the srand() function which you will also need.

Then search these forums -- there's lots of code showing how to use random numbers.

but they're still not random.

>there's no such thing as a random number
100% accurate and 0% helpful.

>but they're still not random.
I don't think anybody here cares but you. If it looks random and acts random for your application, it's random.

yeah, try developing any sort of cryptographic tool with that mindset.

commented: OK -- enough. You aren't making your point so drop it. -2

>yeah, try developing any sort of cryptographic tool with that mindset.
You should work on reading for comprehension. Allow me to quote with emphasis, because you clearly didn't bother to understand what I wrote:

If it looks random and acts random for your application, it's random.

So you can bring up whatever applications you think require truly random numbers in an attempt to prove yourself right, but keep in mind that it's nothing more than a straw man.

I want to know a small c code to generate random numbers.It could be within a certain range.
I want to know if rand() function will generate a random number

For what purpose will these numbers be used?

If they are just going to be dummy numbers to fill an array for the testing of a program, rand() should do fine. If you want numbers within a certain range, or a certain distribution, etc., you will have to do some scaling.

now walt, why you gotta keep hatin on my green dot? does it give you a rush of power?

hey, vardhani, heres a code segment that is 74% accurate and 81% helpful: change the line where "RANGE" is #define'd if you want to randomize from a different set of values.

#include <stdio.h>
#include <stdlib.h>

#define RANGE 100  // for values from 0-99

int main()
{
   int myNum;
   char s[10];
   srand(time());   // "seeds" the generator
            
   while(1) // infinite loop (use CTRL-C to break)
   {     // reasonably random number between 0 and RANGE-1
        myNum = (int)((double)rand()/(((double)RAND_MAX + 1.0)/ (double)RANGE));
      printf("my random number is %02d", myNum);
      gets(s);   // just wait for <enter>
   }  // end while
   return 0;
}

whatever you do, don't let anyone tell you to use myNum = rand() % RANGE; if they tell you to use that, theyre either ignorant or trying to hurt you.

>srand(time());
1) You forgot to include time.h, which hides #2
2) The time function takes an argument. I think you meant time ( NULL ) .
3) All this bluster about good randomness and you neglect to properly seed the generator.

>myNum = (int)((double)rand()/(((double)RAND_MAX + 1.0)/ (double)RANGE));
That's pretty ugly. You know that you don't need most of those casts, right? The result of an expression is the type of the longest, floatiest type. So (RAND_MAX + 1.0) will result in a double, and that goes on to affect the division against RANGE, which goes on to affect the division against rand. You can basically remove all of the double casts:

myNum = (int)(rand() / ((RAND_MAX + 1.0) / RANGE));

>printf("my random number is %02d", myNum);
Unlike C++, standard input functions aren't tied to standard output functions. When you call gets, it doesn't flush stdout first. The only way stdout gets flushed is when the buffer is full (not under your control), you flush it explicitly using fflush, or you print a newline. As it is, you can't guarantee that the user will see the output before gets is called and starts blocking. So the user may just see a blank screen with a blinking cursor and have no idea what to do.

>gets(s);
I'm still waiting for your excuse to use gets.

>if they tell you to use that, theyre either ignorant or trying to hurt you.
Or they understand that you're not particularly interested in a perfect distribution and suggest the simplest code. I tend to use and suggest % in general, and only move up when someone wants a stronger solution.

Here's your code with my changes and preferences:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define RANGE 100  /* Support a range of [0,100) */

double uniform_deviate ( int seed );
unsigned time_seed ( void );
int is_done ( void );

int main ( void )
{
  srand ( time_seed() );

  do {
    double r = uniform_deviate ( rand() ) * RANGE;

    printf ( "My random number is %02.0f", r );
    fflush ( stdout );
  } while ( !is_done() );

  return 0;
}

/**
  @brief Forces a random integer into the range of [0,1)
  @param[in] seed Random seed for fitting the value
  @return The fitted value as floating-point
*/
double uniform_deviate ( int seed )
{
  return seed * ( 1.0 / ( RAND_MAX + 1.0 ) );
}

/**
  @brief Calculates an RNG seed from the system time
  @return A unique seed based on the system time
*/
unsigned time_seed ( void )
{
  time_t now = time ( NULL );
  unsigned char *p = (unsigned char *)&now;
  unsigned seed = 0;
  size_t i;

  /* Hash the bytes of the time_t value */
  for ( i = 0; i < sizeof now; i++ )
    seed = seed * ( UCHAR_MAX + 2U ) + p[i];

  return seed;
}

/**
  @brief Pauses for input and notifies on no input
  @return True if input was found, false otherwise
*/
int is_done ( void )
{
  int c;

  do
    c = getchar();
  while ( c != '\n' && c != EOF );

  return c == EOF;
}

Well, technically it's not your code anymore as I've only kept the intent of the program, but you know what I mean. ;)

okay, yes, that's all well and good but as you'll see there's a perfectly reasonable explanation as to why I ...

oh, look. the Queen!

commented: Long live the Queen. Hehe +7
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.