c++使用随机数来决定下一次相遇
c++ using random numbers to decide the next encounter
为完整代码编辑
我正试图制作一款基于文本的rpg游戏,因为我真的很无聊,想测试我的c++"技能"xd
但我对函数srand
和rand
有一个问题,这是一个生成随机数的函数。
我想实现的是,让RNG决定比赛的下一步行动。I.e:
#include <iostream>
#include <windows.h>
#include <string>
#include "conio.h"
#include <time.h>
using namespace std;
void GetRandom();
int main()
{
int x;
string name;
srand(time(NULL));
cout << "welcome to adventurers world!" << endl;
cout << "you wake up on an island far far away and you don't know where you are" << endl;
Sleep(2000);
cout << "Please enter the name of your adventurer" << endl;
getline(cin, name);
cout << "hello " << name << endl;
Sleep(1000);
cout << "where would you like to go, " << name << " ?" << endl;
Sleep(1000);
cout << "1. waddle around the beachn2. go to the cave straight aheadn3. go into the forest" << endl;
cin >> x;
if(x==1)
{
cout << "you waddle abit around on the beach, and you suddenly " << random;
}
_getch();
}
void random()
{
srand(time(NULL));
int randnumber = rand() % 2 + 1;
randnumber = randnumber;
if(randnumber == 1)
{
cout << "you encounter a mudcrab" << endl;
}
else if (randnumber == 2)
{
cout << "you find a stick" << endl;
}
}
我想在这里实现的是,如果生成的随机数是1 do(randnumber == 1
(,如果是2,do(randnumber == 2
(
但它只是给我一个十六进制作为输出。
我的代码写得正确吗?我是否对srand
使用了正确的表达式,即计算w/e
。
这样做可能吗?还是我必须手动写下接下来会发生什么,这不会让它成为一个动态游戏。
感谢您的帮助和时间
目前,您不是随机调用函数,而是显示其地址。试试这个:
if(x==1)
{
cout << "you waddle abit around on the beach, and you suddenly ";
random();
}
-
不要每次需要一个随机数时就给随机生成器设定时间。除非使用间隔很长时间(超过一秒钟(,否则会将种子设置为相同的值。
-
不要将函数命名为
random()
。这将使random((函数无法访问。它可能应该是choose_random_object()
或类似的东西。 -
在程序开始时为随机数生成器设定一次种子,只有在需要重复随机数时才对其进行种子设定(在这种情况下不太可能(。
-
调用函数应该返回一个有用的值—而你的不是。调用一个过程(一个不返回值的函数(以获取其副作用,例如打印出一个单词。
以下是您的代码应该是什么样子。这些评论解释了这些变化。
srand(time(NULL)); // srand() needs only to be called once in the beginning.
if(x == 1)
{
cout << "you waddle abit around on the beach, and you suddenly ";
GetRandom(); // call the function to output what you need.
}
void GetRandom() // change the name of the function.
{
int randnumber = rand() % 2 + 1;
// no need for: randnumber = randnumber;
if(randnumber == 1)
{
cout << "you encounter a mudcrab" << endl;
}
else // no need for else if since the random # cannot be anything else but 2
{
cout << "you find a stick" << endl;
}
}
相关文章:
- 我是否需要在下一次转移时将所有权*转移回转移队列
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 在C++中一次将矢量值写入多个文件
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 为什么 zlib 放气初始化调用一次不起作用?
- 在一次迭代中从 txt 文件中读取多行
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- 在头文件和 cpp 文件中使用一次 #pragma 时出现结构重定义错误
- 有没有办法一次声明相同类型的多个对象,并通过一个表达式立即使用相同的右值初始化它们?
- 高级选择排序 - 在一次迭代中搜索两个元素
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- 如何仅使用一次固定<<设置精度(2)?或者至少恢复到默认行为?
- 什么是仅调用一次并调用参数的控制台应用
- 如何确保用户在一行上提示输入一次时输入名字和姓氏?
- (C++)虽然循环一次不起作用,但我引入了多个变量
- 为什么我的信号处理程序只执行一次?
- 如何使用C++一次读取整个二进制文件
- 花括号使循环运行一次?
- 从子菜单返回后,正确的输入至少进入验证循环一次
- c++使用随机数来决定下一次相遇