简体   繁体   中英

Switch function not working in C++

Super beginner at C++ here, so forgive me if this code is horribly ugly.

string enemy;
int num;
num = rand()%(5);

switch (num)
{
case 1: enemy = "Ogre";
    break;
case 2: enemy = "Goblin";
    break;
case 3: enemy = "Orc";
    break;
case 4: enemy = "Dark Elf";
    break;
case 5: enemy = "Lizardman";
    break;
}

Basically what is supposed to happen is that, depending on what the random number is, case is chosen that is that number at sets the variable "enemy" to what the case is. However after a bit of debugging I found the only case that showed up was the first one. I googled around for an answer but all of them said the only thing I needed was a break (which I already had). What's wrong with my code?

This doesn't work because rand() values are ranging from 0 to 4, since rand() returns a value between 0 and RAND_MAX and you're dividing it by 5.

To fix this, simply change

num = rand()%(5);

to

num = rand()%(5) + 1;

Also, you might want to seed your rand() function to get better results using

srand(time(NULL)); // requires #include <ctime>

You need to call srand first

srand() seeds the pseudo-random number generator used by rand(). If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1)

see link

That's why you always get 1 as result.

srand(time(0)); //use current time as seed for random generator
num = rand() % 5;

The standard rand() function is a very simple and fast pseudo-random number generator, usually an LCG for most implementations. So it is not unusual for it to return repeated numbers when you trim the upper/lower bounds to a short range as you did.

That said, I think what you are looking for may be the srand() function, which will change the random seed and possibly give you a better distribution if you seed it with the current time, for example.

Another thing, the way you are using it, you will get a number in the range [0,4]. To get a number in the range [1,5], the correct would be rand() % 5 + 1 . See this link for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM