如何从数组中随机生成一个数字,然后在 C++ 的 switch 语句中使用该数字?
How do you randomly generate a number from an array and then use that number in a switch statement in C++?
我是 c++ 的新手,我想随机选择一个案例来使用,但它会直接进入默认状态。如果有人能告诉我我做错了什么或者更好的方法,我将不胜感激。这是我的代码:
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;
}
}
};
//我的srand在我的main函数中。
您的代码中有 2 个问题。
首先,在这一行:
int randIndex = 1 + (rand() % 4) ;
您正在 1 .. 4
范围内生成索引,但您需要 0 .. 3
。所以简单地删除 + 1
这样的:
int randIndex = rand() % 4;
其次,这个作业:
villainArray[randIndex] = theRandomChoice;
不修改 theRandomChoice
。你需要做的:
theRandomChoice = villainArray[randIndex];
我是 c++ 的新手,我想随机选择一个案例来使用,但它会直接进入默认状态。如果有人能告诉我我做错了什么或者更好的方法,我将不胜感激。这是我的代码:
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;
}
}
};
//我的srand在我的main函数中。
您的代码中有 2 个问题。
首先,在这一行:
int randIndex = 1 + (rand() % 4) ;
您正在 1 .. 4
范围内生成索引,但您需要 0 .. 3
。所以简单地删除 + 1
这样的:
int randIndex = rand() % 4;
其次,这个作业:
villainArray[randIndex] = theRandomChoice;
不修改 theRandomChoice
。你需要做的:
theRandomChoice = villainArray[randIndex];