1
#include <iostream> #include <stdlib.h> #include <ctime> int main() { // Create a number that's 0 or 1 srand (time(NULL)); int coin = rand() % 3; // If number is 0: Heads // If it is not 0: Tails if (coin == 0) { std::cout << "Heads\n"; } else { std::cout << "Tails\n"; } } 

Does this mean that there is a 1/2 chance? Could someone thoroughly explain this to me.----> int coin = rand() % 2; What if i were to change this to int coin = rand() % 3; what exactly does this translate to. Could someone explain this to me with other examples.

1
  • 1
    The modulo operator on an integer returns the remainder of the division of lhs by rhs (left hand side and right hand side respectively). rand() returns an unsigned integer between 0 and RAND_MAX, which is at least 32,767. What's the maximum remainder you can have if you're dividing something by two? By three? You could have found this out yourself by searching for "what does rand() return" and "how does modulo work" en.cppreference.com/w/cpp/numeric/random/rand en.cppreference.com/w/cpp/language/operator_arithmetic Commented May 16, 2020 at 4:41

1 Answer 1

1

Simply, the % operator scales the random number into the range you want.

For example, if you are writing as rand() % 3, then the output of this line will be either 0, 1 or 2 only. (try to put any specific value in place of rand() )

  • If you put 2 instead of 3 in rand() % 3 statement, then there will be only two possible outcomes i.e. 0 or 1.
  • Now, for any number in place of 3, the number of possible outcomes become N where N is in place of 3.

in case of your program, you want either a HEADS or TAILS i.e two possible outcomes. By putting 2 instead of 3 in rand() % 3 statement, the variable 'coin' can have only two possible values i.e. 0 or 1

try playing with this code:

#include<iostream> #include<stdlib.h> #include<ctime> int main() { srand (time(NULL)); int rnd = rand(); int coin = rnd % 2; std::cout<<"The value of coin is: "<<coin<<'\n'; return 0; } 

You will observe that, this program will only print either:

  • The value of coin is: 0 OR
  • The value of coin is: 1

I hope you got the answer, Juan.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.