Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/153.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在switch语句中使用rand()_C++ - Fatal编程技术网

C++ 在switch语句中使用rand()

C++ 在switch语句中使用rand(),c++,C++,我一直在写一个随机化程序,但是当我把一个随机化函数,rand()放入其中时,输出总是一样的。它是用C++编写的。例如: #include <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> using namespace std; int main() { srand(time(NULL)); int genre, rVal, rCat; cin&g

我一直在写一个随机化程序,但是当我把一个随机化函数,rand()放入其中时,输出总是一样的。它是用C++编写的。例如:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
    srand(time(NULL));
    int genre, rVal, rCat;
cin>> genre;

switch(genre){
        case '1' :
            rVal = rand() % 7;
            rCat = rand() % 3;
            break;
        case '2' :
            rVal = rand() % 2;
            rCat = 1;
            break;
        case '3' :
            rVal = rand() % 4;
            rCat = 1;
            break;
        case '4' :
            rVal = rand() % 7;
            rCat = rand() % 3;
        if(rVal<=3 && rCat == 1)
            {
                rVal = 1;
                                };
            break;
        case '5' :
            rVal = 1;
            rCat = 1;
        break;};
        cout<< rVal << rCat;};

#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
srand(时间(空));
int体裁、rVal、rCat;
cin>>体裁;
切换(类型){
案例“1”:
rVal=rand()%7;
rCat=rand()%3;
打破
案例“2”:
rVal=rand()%2;
rCat=1;
打破
案例“3”:
rVal=rand()%4;
rCat=1;
打破
案例“4”:
rVal=rand()%7;
rCat=rand()%3;

如果(rVal你确定类型是字符吗?你的开关测试“1”不是1..

欢迎使用堆栈溢出!请用一个或你是否在代码中调用了
srand()
?正如@Yksisarvinen指出的,没有srand()srand(time(NULL))C/C++中的rand()将永远无法工作在顶部主函数的代码中,它甚至可以与除switch语句中的随机函数之外的所有其他随机函数一起工作。问题与
rand()
无关。问题在于
genre
类型为
int
,所有的切换案例都是
char
文本(例如,
'1'
而不是
1
)。因此,如果用户输入
1
,则不会到达任何案例。哦,哇,我以为您会在开关案例中输入“”,但这是问题类型不是字符,而是一个整数,默认案例会发现这一点。