Hello, I've found a lot on the internet about generating random numbers but none of it really does make sense to me, since I'm new to C. All I need is to generate a random number from 0 till 2. So 0,1 or 2 should be the outcome. From what I've been reading, the rand() function in stdlib.h would always give me the same number, is it true? I would just do this... #include <stdlib.h> int x; void main(void){ while(1){ ... x=rand(); ... } } Code (markup):
try this one #include <stdio.h> #include <stdlib.h> #include <time.h> // for time() // Generate a random number between nLow and nHigh (inclusive) unsigned int GetRandomNumber(int nLow, int nHigh){ return (rand() % (nHigh - nLow + 1)) + nLow; } void main(){ int i; srand(time(0)); // set initial seed value to system clock // Generate 100 random numbers for (i = 0; i < 100; i++){ printf("%d\t", GetRandomNumber(0, 3)); } }
Thanks, just what I need. One problem, I do not have time.h but only timers.h, is time() included in timers.h as well?
time.h is a standard header file that comes with almost every C/C++ compiler package I know. Double check that.
I've installed Microchip C18 Compiler and I double checked, no time.h is in the h folder. Opening the file: nearly only defines are in it... no time() function. EDIT: Can't I use anything else than the time? Would it not work if I just use a timer (which counts milliseconds) as seed (it's already present in my program)? Are there any limits concerning the seed?
You would have told it is for embedded Here is the solution for you Random number generator for microcontrollers (PIC, Atmel)
Sorry NeoCambell, I didn't know it was called that way. As before, I'm new to this But yes, that's what I need I guess.. So, changing following line of code would give me a number being 0, 1 or 2: return genrand_int32()*(2.0/4294967295.0); // [0,1]*2 => [0,2] Thanks !