Solved

random byte 0-6

Posted on 2004-11-26
230 Views
I want to randomly pick a byte from 0 to 6 not sure how to do this.
0
Question by:WackoMike

LVL 86

Assisted Solution

You could use

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

typedef unsigned char BYTE;

BYTE RandomByteFrom0To6() {

int i = rand() * 6 / RAND_MAX; // create a random number and map it to the range 0-6

return (BYTE) i;
}

and call it like

int main( void )
{
BYTE i;

/* Seed the random-number generator with current time so that
* the numbers will be different every time we run.
*/
srand( (unsigned)time( NULL ) );

/* Display 10 numbers. */
for( i = 0;   i < 10;i++ )
printf( "  %1.1d\n", RandomByteFrom0To6() );

return 0;
}
0

LVL 55

Accepted Solution

int main()
{
int randomnum;

srand(time(NULL));

// Do work here that uses rand(), for example
for (int i= 0; i< 10; i++)
{
randomnum = rand() % 7;
printf("%i\n\r", randomnum);
}

return 0;
}
0

LVL 55

Expert Comment

oops! a minute later.
0

LVL 7

Expert Comment

Yes jaime, but your example should work.
0

LVL 55

Expert Comment

You will need some headers, here is a fully tested code:

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

int main()
{
int randomnum;

srand(time(NULL));

// Do work here that uses rand(), for example
for (int i= 0; i< 10; i++)
{
randomnum = rand() % 7;
printf("%i\n\r", randomnum);
}

return 0;
}
0

LVL 86

Expert Comment

>> Yes jaime, but your example should work.

Both will work.
0

Author Comment

since you both answer so quick i gave you both 250 i hope that is ok with you guys. Thanks for the help!
0

Featured Post

Suggested Solutions

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.