CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Hybrid View

  1. #1
    Join Date
    Jan 2008
    Posts
    60

    Random Number function problem

    I have a function like such

    Code:
    #include <cstdlib>
    
    inline int randInt(int limit)
    {
        return limit <= 1 ? 0 : (rand() % limit);
    }
    And i use it as followd
    Code:
    if(randInt(2) == 1)
    {
       column = ((randInt(2) == 1) ? (lastTemp.c + randInt(4)) :   (lastTemp.c - randInt(4)));
       row = lastTemp.r;
    }
    else
    {
      column  = lastTemp.c;
      row = ((randInt(2) == 1) ? (lastTemp.r + randInt(4)) : (lastTemp.r - randInt(4)));
    }
    And my lastTemp.c and latTemp.r are both = 0;
    I get the same sequence every time. which is
    r - c
    0 - 0
    0 - 3
    1 - 0
    2 - 1
    0 - 2
    3 - 0

    how come i dont get 2 - 0 ?

  2. #2
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: Random Number function problem

    Try stepping through in the debugger.

    Until you get it working, you may want to try to simplify your code so you don't have so much going on one one line. You may have more lines of code, but sometimes that's a good tradeoff to make it more readable and easier to debug.

  3. #3
    Join Date
    May 2008
    Posts
    96

    Re: Random Number function problem

    Your code looks fine to me.

    I suspect that you forgot to call srand( time( NULL ) ); at the beginning of your program.

    Hope this helps.

  4. #4
    Join Date
    Nov 2003
    Posts
    1,902

    Re: Random Number function problem

    Excellent information on using rand() - http://www.eternallyconfuzzled.com/a..._art_rand.aspx

    gg

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured