-6

I am trying to make when user types number, program should repeat that many times chosing random if Here is my code

cin >> d;
c = 0;

while (c < d) {
    c = c++;
    num = (rand() % 3) + 1;
    if (num == 1) {
        system("start C:\\viewver\\vw");
        Sleep(2000);
    }
    else if (num == 2) {
        system("start C:\\viewver\\vw2");
        Sleep(2300);
    }
    else if (num == 3) {
        system("start C:\\viewver\\vw3");
        Sleep(1800);
    }

It always chooses to open first one and then stops.

Dokido
  • 15
  • 1
  • 1
  • 5

1 Answers1

0

Use == not =

if (num == 1) {
    system("start C:\\test\\vw");
    Sleep(2000);
}
else if (num == 2) {
    system("start C:\\test\\vw2");
    Sleep(2300);
}
else if (num == 3) {
    system("start C:\\test\\vw3");
    Sleep(1800);
}

== is for comparison, = is for assignment


The reason why it always chooses the first option is because C++ (and C) has the notion of truthy values. So any value that is not 0 is considered truthy, whereas values that evaluate to 0 are considered falsy.

In your original code, when you assign num to 1, the value of num is truthy, therefore that branch is always taken

smac89
  • 39,374
  • 15
  • 132
  • 179