i want to write a random function that returns different values in every run.and also takes a variable that defines the limits of the random number.
ex:
random1(100)
it returns a floating points from 0 to 100
i want to write a random function that returns different values in every run.and also takes a variable that defines the limits of the random number.
ex:
random1(100)
it returns a floating points from 0 to 100
Perhaps you could find answers to this common question by searching these boards.
-Prelude
My best code is written with the delete key.
Just create a random number of any any value and then use the modulas operator (%) to mod it by 101. Very simple.
ps. If you don't know how to create a random number, there us function is the standard library calle rand() that wiil do this. (it is not a truely random number though)
'During my service in the United States Congress, I took the initiative in creating the Internet.' - Al Gore, March 9, 1999: On CNN's Late Edition
>Just create a random number of any any value and then use the
>modulas operator (%) to mod it by 101. Very simple.
Assuming you're talking about something like this:
r = rand() % 101;
If not, ignore the rest of this post. There's a problem when using % with rand, it's not very random with lower ranges when you use the low order bits that a construct like this works with. So when you're not working with very large ranges of values, you should use the high order bits by dividing from RAND_MAX. Run this a few times and you'll see that using % with rand isn't quite as random as you may prefer.
-PreludeCode:#include <time.h> #include <stdio.h> #include <stdlib.h> int main ( void ) { int x; srand ( (unsigned)time ( NULL ) ); for ( x = 0; x < 10; x++ ) { printf ( "%d\t", ( rand() * 5 ) / RAND_MAX ); printf ( "%d\n", rand() % 5 ); } return EXIT_SUCCESS; }
My best code is written with the delete key.
>r = rand() % 101;
That is exactly what I meant.
Sorry for the bad advice.
Here is a function that should work i think. I found it in an old
homework assignment of mine. Right now it returns an integer value, so I will leave changing it to a float up to him.
Code:int RandomInt(int low, int high) { if (low > high) { printf("RandomInt: low cannot be greater than high.\n"); exit(0); } return (high - low + 1) * (rand() / (double) INT_MAX) + low; }
'During my service in the United States Congress, I took the initiative in creating the Internet.' - Al Gore, March 9, 1999: On CNN's Late Edition