C++函数和随机数
C++ functions and random number
当我写这个代码时:
#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());
}
}
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++ 随机数生成器:尝试将结果作为向量获取,但通过制作 void 函数来执行此操作而出现错误
- 随机数生成函数说明
- C++随机数分布传递给函数
- 每次调用函数时,随机数都相同
- 创建整数的 2D 数组,该数组将使用两个函数用随机数填充矩阵.我做错了什么?
- 我需要线程函数在不停止实际程序的情况下,每2秒打印一次随机数
- C++ 在函数中生成随机数
- 用于创建高斯随机数的 c++ 函数
- C++11 中的随机数:有没有一种简单的方法可以将生成器种子放在代码的一个位置,然后在不同的函数中使用它?
- 为什么这4个不同的随机数生成器函数会产生相同的一系列数字
- 是否有在 c++ 中使用三角分布生成随机数的函数
- 将范围随机数保存到数组而不重复的函数
- 传递参数、参数、交换函数和随机数生成器
- 随机数函数未正确随机化 (C++)
- c++11 子函数中的随机数生成器
- rand()在通过函数调用时生成相同的随机数集(即使在使用srand(time(NULL)进行种子设定之后)
- 函数用于随机数(C++11)
- 提升C++:在函数中播种随机数
- C++循环中调用伪随机数生成器函数 - 常量种子问题