![]() |
| ||
| Helping with calling a function I wrote this function to generate random numbers and return it to the calling function int getCard(void)but for some reason firstCard and secondCard always have the same value. I am not sure why. Can anyone help me out? |
| ||
| Re: Helping with calling a function I think it's to do with where you seed rand. I'm not absolutely certain, but I think (note, this wasn't compiled so it mightn't), this should work - int getCard(void) |
| ||
| Re: Helping with calling a function wow, thank you twomers!! it works. Would you mind explaining a little bit of why you needed to add.... static bool is_set; if ( !is_set ) { is_set = true; srand(time(NULL)); } else is_set = false; and also why it wasn't working the way I had it at first? |
| ||
| Re: Helping with calling a function Have you ever tried calling rand() without seeding it? If not use a loop and call it ten times. Note the results. Then execute your program again and look at the results. You should notice the same numbers coming up: int main( void ) (also, could you use code tags? It makes code easier to read.) I'm not certain, as I said, but I think you're calling the functions quite fast after one another, so perhaps they're getting seeded with the same value ... int main( void ) so it shoots out the same numbers. Remember it's not truly random. Just pseudo-random |
| ||
| Re: Helping with calling a function I just choose the value 42 there. You could use any number and I *think* you should get the same numbers. So I reckon the time(NULL)'s were returning the same number each time. The static type ... you should do some reading on it. It basically doesn't really go out of scope when the function ends. It kind of globalises local functions within a set scope, in a sense. So the boolean value (is_set), is there. Then I test it as to whether it's true or not. If it isn't I seed rand with one value and then set its value to true. This means for the rest of the duration of the program it's value is true which means it doesn't get seeded again with the same value. |
| ||
| Re: Helping with calling a function >and also why it wasn't working the way I had it at first? Did you include <stdlib.h> and <time.h>, the first time?. Most like you missed <stdlib.h> if I were going to guess. Take the srand() function out of the getCard(). Call srand( (unsigned) time( NULL ) ) inside main() just one time. That's all you need, not every time that you call the getCard() function. |
| All times are GMT -4. The time now is 7:24 pm. |
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC