-4

当我写这段代码时:

#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++ 新手。

4

2 回答 2

4

全局初始化器在调用之前执行。 main所以你永远不会重新播种你的 PRNG,因此总是绘制相同的“随机”数字。

也就是说,我不相信您的任何一个代码段在每次运行时都会产生不同的输出,因为它们具有相同的初始化顺序问题。

于 2013-06-30T20:11:23.480 回答
0

编辑:更改以匹配您声明的“bear”、“bearr”、“pig”、“pigg”目标。

int random = std::rand() % 9 + 1;

声明了一个名为“random”的全局变量,它在启动期间在 main() 之前分配了一个值。该值将是(rand() 的默认返回值以 9 为模)加一。它不会自动更改。

您似乎正在寻找的是

int random()
{
    return (std::rand() % 9) + 1;
}

它定义了一个调用 rand 的函数,将值乘以 9,然后返回 1。编辑:要在“func()”函数中查看相同的值,请通过值或引用将其作为函数参数传递:

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using std::cout;
using std::endl;

int random() {
    return (std::rand() % 9) + 1;
}

void func(int randNo){
    switch (randNo) {
        case 1: case 2: case 3:
            cout << "Wolff" << endl;
        break;
        case 4: case 5: case 6:
            cout << "Bearr" << endl;
        break;
        case 7: case 8: case 9:
            cout << "Pigg" << endl;
        break;
    }
}

int main()
{
    std::srand(std::time(0));

    int randNo = random();
            switch (randNo) {
        case 1: case 2: case 3:
            cout << "Wolf" << endl;
            func(randNo);
        break;
        case 4: case 5: case 6:
            cout << "Bear" << endl;
            func(randNo);
        break;
        case 7: case 8: case 9:
            cout << "Pig" << endl;
            func(randNo);
        break;
    }

            cout << "And now for something completely different." << endl;
    for (size_t i = 0; i < 10; ++i) {
        cout << i << ": ";
        func(random());
    }
}
于 2013-06-30T21:43:36.290 回答