Why does this not work?

Why does this allways cout rock.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <time.h>
#include <cstdlib>

using namespace std;

int main()
{
    char play;
    string person;
    string computer;
    srand(time(NULL));
    int i = rand()%3;

    if(i=0)
    {
        computer="paper";
    }
    else if(i=1)
    {
        computer="rock";
    }
    else if(i=2)
    {
        computer="scissors";
    }

cout<<computer<<endl;
}
Last edited on
Do you know that the operator= is the assignment operator and that the operator== is the comparison operator?

Omg yes! I completely forgot... Ty
closed account (E0p9LyTq)
You are assigning (=) instead of comparing (==) in your if statements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>

int main()
{
   // char play;
   // std::string person;
   std::string computer;
   srand(time(0));

   int i = rand() % 3;

   if (i == 0)
   {
      computer = "paper";
   }
   else if (i == 1)
   {
      computer = "rock";
   }
   else if (i == 2)
   {
      computer = "scissors";
   }

   std:: cout<< computer <<std::endl;
}

closed account (E0p9LyTq)
You really shouldn't use the C library random functions srand() and rand(). The C standard recommends not using them.

C++ has a wide variety of class templates for creating random numbers in the <random> header, that have none of the deficiencies of rand():
http://www.cplusplus.com/reference/random/
(lots of examples how to use)

Using a switch statement is less error prone over using multiple if/else if statements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <chrono>  // for seeding the random number engine
#include <random>  // for random number engine and distribution
#include <string>

int main()
{
   // char play;
   // std::string person;
   std::string computer;

   // obtain a seed from the system clock:
   unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();

   // create a random generator, seeding it
   std::mt19937 rng(seed);  // mt19937 is a standard mersenne_twister_engine

      // create a uniform int distribution, between 1 and 3
      std::uniform_int_distribution<int> dist(1, 3);

      for (size_t loop = 0; loop < 10; loop++)
      {
         // generate a random number, using the engine and distribution
         int i = dist(rng);

         switch (i)
         {
         case 1:
            computer = "paper";
            break;

         case 2:
            computer = "rock";
            break;

         case 3:
            computer = "scissors";
         }

         std::cout << computer << std::endl;
      }
}


rock
rock
paper
scissors
scissors
scissors
paper
rock
paper
paper
Last edited on
Topic archived. No new replies allowed.