C++函数和随机数

C++ functions and random number

本文关键字:随机数 函数 C++      更新时间:2023-10-16

当我写这个代码时:

#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 Bear、Wolff或Pig Pigg。但有了这个功能,无论何时运行它,我都会得到相同的结果。问题出在哪里
请帮帮我,我是C++新手。

全局初始化程序在调用main之前执行。所以你从来没有重新设定你的PRNG,因此总是画相同的"随机"数字。

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

EDIT:更改以匹配您的既定目标"bear"、"bearr"、"pig"answers"pigg"。

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

声明一个名为"random"的全局变量,该变量在main()之前的启动过程中被赋值。该值将是(rand()的默认返回值以9为模)加1。它不会自动更改。

你似乎在寻找

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

它定义了一个调用rand的函数,将值取模9,然后返回1。EDIT:要在"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());
    }
}