当我写这段代码时:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int random = std::rand() % 9 + 1;
int main()
{
std::srand(std::time(0));
if(random==1 || random ==2 || random == 3){
cout << "Wolf" << endl;
} else if(random==4 || random ==5 || random == 6){
cout << "Bear" << endl;
} else if(random==7 || random ==8 || random == 9){
cout << "Pig" << endl;
}
}
每次我运行它时,我都会打印出我想要的其他东西(狼、猪或熊)。但是当我像这样在我的代码中添加这个函数时:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int random = std::rand() % 9 + 1;
void func(){
if(random==1 || random ==2 || random == 3){
cout << "Wolff" << endl;
} else if(random==4 || random ==5 || random == 6){
cout << "Bearr" << endl;
} else if(random==7 || random ==8 || random == 9){
cout << "Pigg" << endl;
}
}
int main()
{
std::srand(std::time(0));
if(random==1 || random ==2 || random == 3){
cout << "Wolf" << endl;
func();
} else if(random==4 || random ==5 || random == 6){
cout << "Bear" << endl;
func();
} else if(random==7 || random ==8 || random == 9){
cout << "Pig" << endl;
func();
}
}
我希望每次运行它都能打印出其他东西,比如 Bear Bearr、Wolf Wolff 或 Pig Pigg。但是每当我运行这个函数时,我都会得到相同的结果。有什么问题?
请帮助我,我是 C++ 新手。