首页 > 解决方案 > How do you randomly generate a number from an array and then use that number in a switch statement in C++?

问题描述

I am very new to c++ and I am trying to randomly pick one of my cases to use, but it is going straight to default. I would appreciate it if someone could tell me what I am doing wrong or maybe a better way to do it. This is my code:

class selectingTheVillain {
public:
void theRandomness() {

int theRandomChoice;

int villainArray[4] = {0, 1, 2, 3};

int randIndex = 1 + (rand() % 4) ;

villainArray[randIndex] = theRandomChoice;


cout << "Welcome to the Random Dungeon Game!" << endl << endl;

switch (theRandomChoice) {
case 0:
class skeleton skeleton;
skeleton.setSkeletonStats(170, 40, 20, 5);
skeleton.showSkeletonStats();
break;

case 1:
class goblin goblin;
goblin.setGoblinStats(160, 40, 50, 15);
goblin.showGoblinStats();
break;

case 2:
class ghoul ghoul;
ghoul.setGhoulStats(130, 45, 30, 30);
ghoul.showGhoulStats();
break;

case 3:
class stoneGolem stoneGolem;
stoneGolem.setStoneGolemStats(220, 45, 5, 0);
stoneGolem.showStoneGolemStats();
break;

default:
cout << "It did not work" << endl;
break;
}
}
};

//my srand is in my main function.

标签: c++switch-statementsrand

解决方案


You have 2 issues in your code.

Firstly, on this line:

int randIndex = 1 + (rand() % 4) ;

you are generating indexes in the range 1 .. 4, but you need 0 .. 3. So simply remove the + 1 like this:

int randIndex = rand() % 4;

Secondly, this assignment:

villainArray[randIndex] = theRandomChoice;

doesn't modify theRandomChoice. You need to do:

theRandomChoice = villainArray[randIndex];

推荐阅读