rhitx said:
I'm trying create a random number generator, which will generate
either number 1, 2, 3.
I tried to do it like:
int random_number()
{
int no_goal, rand_Number;
rand_Number = rand();
no_goal = (rand_Number % 3);
return no_goal;
}
But it is only generating the digit "1", I don't see it changing to 2
or 3.
It worked when I tried it.
First, a few comments on your code.
The declaration "int random_number()" is legal, but
"int random_number(void)" is clearer and more explicit.
You don't need those temporary variables. The following version of
your function is both shorter and clearer:
int random_number(void)
{
return rand() % 3;
}
Here's a small program I wrote that uses this function:
#include <stdio.h>
#include <stdio.h>
int random_number(void)
{
return rand() % 3;
}
int main(void)
{
int i;
for (i = 0; i < 30; i ++) {
printf(" %d", random_number());
}
putchar('\n');
return 0;
}
And here's its output (I got the same results with your more verbose
version of the function):
0 2 0 2 2 0 0 1 0 2 1 0 2 0 2 0 2 0 0 2 2 1 2 2 2 1 1 0 0 0
So why are you getting 1 every time? It must be something in the code
you didn't show us. My best guess is that you're calling srand() once
for each call to rand(). Don't do that. srand() is used to
initialize a sequence of random numbers; normally, you should only
call it once in the entire execution of your program. Consult your
documentation for the rand() and srand() functions.
See also the comp.lang.c FAQ, <
http://www.c-faq.com/>, questions 13.15
through 13.21.