Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 136,067 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,588 people online right now. Registration is fast and FREE... Join Now!




Why won't the seeded rand function change between function calls?

 
Reply to this topicStart new topic

Why won't the seeded rand function change between function calls?

camaroer87
13 Apr, 2008 - 03:24 PM
Post #1

New D.I.C Head
*

Joined: 13 Mar, 2008
Posts: 40

I call this function 10 times in my program, but the random numbers never change between calls. Why not and how can I fix this?

CODE

void placeShips(char gameBoard[][COLUMNS], char ship, int strength)
{
    int i, c, row, col, horizPlace;
    
    
    //seed random number generator
    srand(time(NULL));
    
    //decide wether ship will be horizontaly or verticly aligned
    horizPlace = (rand() % 2);
    
    //randomly pick a starting point for a ship
    row = (rand() % 10);                            //HERE
    col = (rand() % 10);                             //AND HERE
        
    if (gameBoard[row][col] == '~')
    {
        gameBoard[row][col] = ship;
    
        if (horizPlace == YES)
        {
            for(c = 1; c < strength; c++)
                gameBoard[row][col + c] = ship;
        }
        else
        {
            for(c = 1; c < strength; c++)
                gameBoard[row + c][col] = ship;
        }
    }
    
    printf("\n \n %d %d", row, col);
}


This post has been edited by camaroer87: 13 Apr, 2008 - 03:25 PM
User is offlineProfile CardPM
+Quote Post

KYA
RE: Why Won't The Seeded Rand Function Change Between Function Calls?
13 Apr, 2008 - 04:30 PM
Post #2

#include <nerd.h>
Group Icon

Joined: 14 Sep, 2007
Posts: 4,777



Thanked: 91 times
Dream Kudos: 1200
My Contributions
Why not seed in main() and see if that helps.

This post has been edited by KYA: 13 Apr, 2008 - 04:31 PM
User is online!Profile CardPM
+Quote Post

camaroer87
RE: Why Won't The Seeded Rand Function Change Between Function Calls?
13 Apr, 2008 - 05:03 PM
Post #3

New D.I.C Head
*

Joined: 13 Mar, 2008
Posts: 40

That worked, thanks! What made the difference?
User is offlineProfile CardPM
+Quote Post

KYA
RE: Why Won't The Seeded Rand Function Change Between Function Calls?
13 Apr, 2008 - 05:10 PM
Post #4

#include <nerd.h>
Group Icon

Joined: 14 Sep, 2007
Posts: 4,777



Thanked: 91 times
Dream Kudos: 1200
My Contributions
Off the top of my head-- no idea. But if I had to wager a guess, the seed goes out of scope once your function returns control back to main so each time it was called it would seed exactly the same way.
User is online!Profile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/1/08 06:45PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month