Like Tree2Likes
  • 1 Post By Salem
  • 1 Post By VirtualAce

Rand().

This is a discussion on Rand(). within the C# Programming forums, part of the General Programming Boards category; Hi, Could anyone please explain to me the following: Code: int a = !(rand () % 3); Is there a ...

  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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,765
    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 );
    vart likes this.
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  4. #4
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,598
    Why is this on the C# forum?
    itsme86 likes this.

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, 05: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, 03:46 PM
  5. rand()
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 07-05-2002, 03:39 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21