c++使用随机数来决定下一次相遇

c++ using random numbers to decide the next encounter

本文关键字:一次 相遇 随机数 决定 c++      更新时间:2023-10-16

为完整代码编辑

我正试图制作一款基于文本的rpg游戏,因为我真的很无聊,想测试我的c++"技能"xd
但我对函数srandrand有一个问题,这是一个生成随机数的函数。

我想实现的是,让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();
}
  1. 不要每次需要一个随机数时就给随机生成器设定时间。除非使用间隔很长时间(超过一秒钟(,否则会将种子设置为相同的值。

  2. 不要将函数命名为random()。这将使random((函数无法访问。它可能应该是choose_random_object()或类似的东西。

  3. 在程序开始时为随机数生成器设定一次种子,只有在需要重复随机数时才对其进行种子设定(在这种情况下不太可能(。

  4. 调用函数应该返回一个有用的值—而你的不是。调用一个过程(一个不返回值的函数(以获取其副作用,例如打印出一个单词。

以下是您的代码应该是什么样子。这些评论解释了这些变化。

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;
    }
}