【发布时间】:2013-06-27 23:31:44
【问题描述】:
当我写这段代码时:
#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();
}
}
我希望每次运行它时都能打印出熊熊、狼沃尔夫或猪猪之类的其他东西。但是每次运行这个函数时,我都会得到相同的结果。有什么问题?
请帮助我,我是 C++ 新手。
【问题讨论】:
-
我不相信你总是“打印别的东西”;看我的回答。此外,这段代码甚至无法在 Posix 上为我编译,因为
random已经在cstdlib中定义。
标签: c++ function random numbers