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

时间:2014-04-29 22:23:50

标签: c++ random srand

已获编辑完整代码

我正在尝试制作一个基于文本的RPG游戏,因为我真的很无聊,想要把我的c ++"技能"在测试xd。
但是我遇到了函数srandrand的问题,这是生成随机数的函数。

我想要实现的目标是让RNG决定下一个游戏动作。我:

#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 beach\n2. go to the cave straight ahead\n3. 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(randnumber == 1),如果为2,则执行(randnumber == 2
但它只是给了我一个十六进制作为输出。

我的代码是否正确编写?我使用srand的正确表达式,计算w/e

这甚至可以做到吗?或者我必须手动写出接下来会发生什么,这不会成为一个动态的游戏。

感谢您的帮助和时间

3 个答案:

答案 0 :(得分:3)

目前,您没有随机调用该功能,您正在显示其地址。试试这个:

if(x==1)
{
    cout << "you waddle abit around on the beach, and you suddenly ";
    random();
}

答案 1 :(得分:2)

  1. 每次需要随机数时,不要随机生成随机生成器。除非使用时间很长(超过一秒),否则会将种子设置为相同的值。

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

  3. 程序开始时将随机数生成器播种一次,只有在需要重复随机数时才重新播种(在这种情况下不太可能)。

  4. 调用函数应该返回一个有用的值 - 您的值不是。为副作用调用一个过程(一个不返回值的函数),例如打印出一个单词。

答案 2 :(得分:0)

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

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