Thread: Rand().

  1. #1
    Registered User
    Join Date
    Apr 2013
    Posts
    122

    Rand().

    Hi,
    Could anyone please explain to me the following:
    Code:
    int a = !(rand () % 3);
    Is there a condition here? What actually forms the condition? Is it the '!'? Why does it return 0 with probability 2/3 (i.e. how does it work)?

  2. #2
    Registered User
    Join Date
    Apr 2013
    Posts
    122
    Can it be interpreted thus - if number is not divisible by 3 a=0, else a=1?

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    In C, any non-zero value is regarded as 'true', so when you have an expression such as
    if ( x )
    there is an implicit
    if ( (x) != 0 )
    going on.

    So the implied inner condition is
    int a = !((rand () % 3) != 0);

    You can then cancel out the negations, and arrive at
    int a = (rand () % 3 == 0 );
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    Why is this on the C# forum?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. rand() again
    By thunderzone in forum C Programming
    Replies: 3
    Last Post: 05-03-2010, 04:17 PM
  2. rand()
    By Livnat in forum C Programming
    Replies: 11
    Last Post: 11-12-2008, 11:29 AM
  3. Difference in Unseeded rand() and seeded rand()
    By relientk_man in forum C++ Programming
    Replies: 5
    Last Post: 11-09-2005, 07:32 AM
  4. rand();
    By nas in forum C Programming
    Replies: 11
    Last Post: 07-10-2002, 02:46 PM
  5. rand()
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 07-05-2002, 02:39 PM