-2

How can I cout 1 or 2 in C++? I would like to cout 1 or 2(randomly choose between them). What do I have to change to work well ? This is not working, because it cout only the 1 number.

#include <iostream>
using namespace std;

int main()
{ cout  << "1" || "2";
return 0;
}
hello16
  • 43
  • 4

1 Answers1

0

For 50/50 chance, you can just use

int randomNumber = (rand() % 2) + 1;
cout << randomNumber << endl;

rand() generates a random positive integer, %2 will make it randomly either 0 or 1, +1 will make it randomly either 1 or 2.

EDIT

As George pointed out in the comment, we need to add a seed to make it truly random, and there are better methods to do it. However, for someone just starting (which I guess the OP is), it is sufficient.

  • 1
    Please see [Why is the use of rand() considered bad?](https://stackoverflow.com/questions/52869166/why-is-the-use-of-rand-considered-bad). Also, the number won't be random without seeding it. – George Nov 15 '21 at 10:52
  • @George thanks for your input. I agree it wont be truly random without seeding it. However, the question seems to have been asked by someone who is just starting out in programming. I didn't want to confuse them with a lot of concepts. – Surya Srivastava Nov 26 '21 at 10:34