我在C ++中有点像初学者,在我的一个类中使用rand()函数时遇到了问题。我希望你能发现什么是错的,因为我没有它就继续努力。以下是导致错误的代码段:
string GetCode::getName()
{
string name;
bool gotoNext = false;
double probability = (double)rand() / RAND_MAX;
cout << probability << endl; //cout the probability and hope that it is a good one this time
if(!setupRan)
setupCharacters();
if(probability < 0.45 && sizeof(regularBoyNames) / sizeof(*regularBoyNames) != 0)
return regularBoyNames[rand() % sizeof(regularBoyNames) / sizeof(*regularBoyNames)];
else if(probability < 0.60 && sizeof(annoyingTeacherNames) / sizeof(*annoyingTeacherNames) != 0)
return annoyingTeacherNames[rand() % sizeof(annoyingTeacherNames) / sizeof(*annoyingTeacherNames)];
else if(probability < 0.80 && sizeof(regularGirlNames) / sizeof(*regularGirlNames) != 0)
return regularGirlNames[rand() % sizeof(regularGirlNames) / sizeof(*regularGirlNames)];
else if(probability < 0.99 && sizeof(teacherNames) / sizeof(*teacherNames) != 0)
return teacherNames[rand() % sizeof(teacherNames) / sizeof(*teacherNames)];
else if(probability < 1 && sizeof(legendaryNames) / sizeof(*legendaryNames) != 0) {
return legendaryNames[rand() % sizeof(legendaryNames) / sizeof(*legendaryNames)];
}
return "failed";
}
当我用cout
输出概率时,我得到一个始终低于0.01的数字,并且通常是相同的。我在构造函数中播种了一次rand:
bool seeded = false;
GetCode::GetCode()
{
if(!seeded) {
srand(time(NULL));
seeded = true;
}
}
rand()
也没有在该计划的任何其他部分播种。以下是GetCode头文件,以备不时之需:
#ifndef GETCODE_H_INCLUDED
#define GETCODE_H_INCLUDED
#include <iostream>
#include <string>
#include "Attack.h"
using namespace std;
class GetCode
{
public:
string getLine(string name);
string getName();
string enemyType();
int healthPoints();
Attack getAttack();
GetCode();
private:
double probability;
};
#endif
如果您需要更多代码,请与我们联系。 即使我试图在没有播种的情况下调用rand(),我总是得到一个大约500的数字,而且它很少会改变。我究竟做错了什么?我到处搜索,找不到任何东西。是否涉及不初始化其他功能?或者某种我缺少的标识符?或者它是功能的双重?我已经尝试了几乎所有我找到的解决方案,但没有任何工作。请帮忙!