This question already has answers here:
srand() — why call it only once?
(7 answers)
C program - srand() [duplicate]
(6 answers)
Closed 3 years ago.
I have this code I need to write, and I created this function. Irrelevant of what it does for the code, I need it to generate a random number (a) between 0 and (i), an integer with a previously initialized value. Somehow despite seeding, I always get the same number.
I have tried entering a number instead of i and it works properly by giving me a different random number each time I execute. I also tried declaring a new int variable inside in the function and giving it the value of i, but it still doesn't work.
elementptr position_current(elementptr first, int i){
elementptr current = first;
int j = 1;
printf("%d\n", i);
srand(time(NULL));
int a = rand() % i;
printf("%d\n",a);
for(j=1;j<a;j++){
current = current->next;
}
return current;
}
I expect (a) to get a different value each Time I run the code, however it's always getting the same value(2).
Can someone tell me what could be wrong?
I'm guessing you're calling this function many times in a single second. Since time only changes once a second, you're reseeding the same value over and over.
Don't call srand over and over. Call it exactly once in your main function, then never call it again, and rand will produce successive values based on that seed one at a time.
Related
This question already has answers here:
Why do I always get the same sequence of random numbers with rand()?
(12 answers)
Closed 10 months ago.
Whenever I run this code, I get a same result.
Program
#include<stdlib.h>
int main(int agrc, const char *argv[]) {
int i = rand();
printf("%d\n",i);
for(i=0;i<10;i++) {
printf("%d\n",rand());
}
}
Result:
41
18467
6334
26500
19169
15724
11478
29358
26962
24464
5705
I ran this on mingw. Actually I am learning Objective-C
Please help me.
You need to seed the rand function with a unique number before it can be used. The easiest method is to use time()
For example
srand(time(NULL));
rand();//now returns a random number
The reason is that the random numbers provided by rand() (or any other algorithm based function) aren't random. The rand function just takes its current numerical state, applies a transformation, saves the result of the transformation as the new state and returns the new state.
So to get rand to return different pseudo random numbers, you first have to set the state of rand() to something unique.
You want to initialize the PRNG.
Initialize it once (typically inside main()) with a call to the srand() function.
If you do not initialize the PRNG, the default is to have it initialized with the value 1. Of course initializing it with some other constant value will not give you different pseudo random numbers for different runs of the program.
srand(1); /* same as default */
srand(42); /* no gain, compared to the line above */
You need to initialize with a value that changes with each run of the program. The value returned from the time() function is the value most often used.
srand(time(NULL)); /* different pseudo random numbers almost every run */
The problem with time(NULL) is that it returns the same value at the same second. So, if you call your program twice at 11:35:17 of the same day you will get the same pseudo random numbers.
Just to add to Yacoby's answer - I was slightly surprised that it didn't default to a time-based seed, so I looked up the man page:
If no seed value is provided, the rand() function is automatically seeded with a value of 1.
So if you change your code to use seed(1) you should still see the same output - but seed(time()) will make it change each time.
The output from rand is pseudo-random, which means that it looks effectively random, but is computed the same way each time, starting from a special value called the seed. With the same seed value, you get the same sequence of random numbers.
To set a different seed, use the standard C function void srand(unsigned int) once in your code before you start generating random numbers. One common way of getting a different sequence of random numbers each time you run the program is to base the seed on the clock time. E.g. srand(clock())
This question already has answers here:
srand() — why call it only once?
(7 answers)
Closed 4 years ago.
so I am trying to fill an array with random integers.
for (int i = 0; i < 2; i++){
srand(time(NULL));
array[i]=rand()%30; }`
Here is my code so far. I am currently getting the same random number twice. Would like to know if there is a way around this?
You seed the PRNG multiple times in the loop. It should be done only once.
By calling srand in the loop you reset the seed. And if you pass the same value to srand then the next call to rand will generate the exact same value.
rand() usually uses a PRNG, which uses the seed to generate the random number. srand ( time(NULL) ); is used to seed the pseudo-random number generator.
Currently, the time granularity of time() is 1 second, so if you seed the PNRG with the same value [time(NULL);] multiple time within the granularity period, call will to rand() generate the same random number.
Move the srand(time(NULL) outside the loop.
This question already has answers here:
unexpected output in C (recursion)
(3 answers)
Closed 4 years ago.
#include <stdio.h>
int main()
{
static int i = 5;
if (--i)
{
main();
printf("%d\n", i); // will this line executes ?
}
return 0;
}
Output:
0
0
0
0
does code below main(); printf statement instructions is placed to stack every time when main recursive calls happens and executed while terminated from this program?
i is reduced by successive calls to main until zero is reached.
Then printf is called for each level of recursion.
(Note that the behaviour of calling main from itself is well-defined although ill-advised in C, in C++ the behaviour is undefined.)
if (--i)
This will evaluate true the first time (--i == 4). The code recurses into main(). (Recursion: A function calling itself.)
As i is static, it will retain its value of 4 (as opposed to an automatic variable, which would be initialized to 5 again). The if (--i) in this second execution of main() will again be true (evaluating to 3), and will again call main() (for a third execution of the function).
The same for --i == 2 and --i == 1, for four executions of main() (including the first, non-recursive one) total that are evaluating the if condition to true.
The next recursion will evaluate the if condition to --i == 0, and thus false. Skipping the if clause, the function call will just return. i is zero at this point, and -- being static, i.e. only one persistent i for all instances of main() -- will remain at that value.
The main() call one level up the stack -- the one that evaluated --i == 1, then called main() and was waiting for it to return -- will now continue with the statement after the call to main(), and printf() the current value of i... which is 0.
The same happens three more times (for a total of four) until the top-most main() returns. You get four times the current value of i, which is 0.
Note that calling main() from your program is allowed in C, but not in C++. This is specifically for calling main() recursively; for other functions, it is allowed in either language.
(--i) will decrease the value of i to 4 when it is called for the first time and it will continue the decrement of i until (i==0) due to recursion.
Since you have declared the variable i with static keyword and hence a single memory is allocated to it and all the changes are reflected back to it
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is really happening in this code?
I have a code which includes a recursive function. I have wasted a lot of time on recursion, but i still couldn't get it, really:
#include<stdio.h>
count(int);
main(){
int x=10,z;
z=count(x);
}
count(int m){
if(m>0)
return count(m-1);
}
When count is called for the first time with argument 10, it fulfils the condition and the recursion starts. What happens really when a function calls itself? I dont get it. What does the statement return count(m-1) mean? Where does it tranfer the control?
The return value of the function count is undefined, because there is no default return if (m <= 0) is true.
C11, § 6.9.1 Function definitions
If the } that terminates a function is reached, and the value of the
function call is used by the caller, the behavior is undefined.
Besides, to understand how a recursive function works, you have to take a paper and try to execute the code by yourself (see also here).
You need count to return something when m <= 0. You should declare the return type of count and compile with -Wall so the compiler will help you find mistakes in your code.
recursion means that the function will call itself, mostly at the end of itself, if it's tail recursion.
So your count function checks that the input argument is > 0 and then if it is, it will call count(m-1). Now it starts at the top of count with m=9. It does the same thing, and then calls count with m=8, etc.
Until the end condition is reached, which should normally be explicitly catered for in your function, such as if (m == 0) return m; or some such thing. At that point the recursion ends and the function terminates.
Also, count should have a return type, such as int count (int m)
what does the statement return count(m-1) mean ? where does it tranfer the control?
That seems to be your only question.
it means that it is calling "count" with the value m-1. So if m was 10, then it is calling "count" with 9.
It is transferring the control recursively to the count method.
You also don't have a return for the every possible path in the "count" method.
What happens if m is <= 0?
This question already has answers here:
Why do I always get the same sequence of random numbers with rand()?
(12 answers)
Closed 10 months ago.
Whenever I run this code, I get a same result.
Program
#include<stdlib.h>
int main(int agrc, const char *argv[]) {
int i = rand();
printf("%d\n",i);
for(i=0;i<10;i++) {
printf("%d\n",rand());
}
}
Result:
41
18467
6334
26500
19169
15724
11478
29358
26962
24464
5705
I ran this on mingw. Actually I am learning Objective-C
Please help me.
You need to seed the rand function with a unique number before it can be used. The easiest method is to use time()
For example
srand(time(NULL));
rand();//now returns a random number
The reason is that the random numbers provided by rand() (or any other algorithm based function) aren't random. The rand function just takes its current numerical state, applies a transformation, saves the result of the transformation as the new state and returns the new state.
So to get rand to return different pseudo random numbers, you first have to set the state of rand() to something unique.
You want to initialize the PRNG.
Initialize it once (typically inside main()) with a call to the srand() function.
If you do not initialize the PRNG, the default is to have it initialized with the value 1. Of course initializing it with some other constant value will not give you different pseudo random numbers for different runs of the program.
srand(1); /* same as default */
srand(42); /* no gain, compared to the line above */
You need to initialize with a value that changes with each run of the program. The value returned from the time() function is the value most often used.
srand(time(NULL)); /* different pseudo random numbers almost every run */
The problem with time(NULL) is that it returns the same value at the same second. So, if you call your program twice at 11:35:17 of the same day you will get the same pseudo random numbers.
Just to add to Yacoby's answer - I was slightly surprised that it didn't default to a time-based seed, so I looked up the man page:
If no seed value is provided, the rand() function is automatically seeded with a value of 1.
So if you change your code to use seed(1) you should still see the same output - but seed(time()) will make it change each time.
The output from rand is pseudo-random, which means that it looks effectively random, but is computed the same way each time, starting from a special value called the seed. With the same seed value, you get the same sequence of random numbers.
To set a different seed, use the standard C function void srand(unsigned int) once in your code before you start generating random numbers. One common way of getting a different sequence of random numbers each time you run the program is to base the seed on the clock time. E.g. srand(clock())