为什么我的第一个项目不是随机的?
Why is my first roll out of my program not random?
这个程序是一个掷骰子的游戏。程序运行得非常好,除了每次程序启动时,它都会给我相同的随机数,但如果你继续玩游戏并在不退出主机的情况下开始新游戏,那么第一个掷出的数字显然是随机的,因为我无法预测again()
函数之后它会是什么,但当代码首次启动时,第一个掷出的数字总是10。我一直在试图自己解决这个问题,我似乎找不到任何一个有骰子游戏编码的人,但也许有人可以在这里帮助我。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
//main prototype
int main();
//score system
int wins = 0;
int loses = 0;
int again(){
int answer;
cout << "nWould you like to play another round? (1=y,2=n)n" << endl;
cin >> answer;
cout << endl;
cout << endl;
if(answer==1){
main();
}else if(answer==2){
cout << "thanks for playing homie" << endl;
return 0;
}else{
cout << "I'm sorry what?" << endl;
again();
}
}//end of again
class DiceClass{
public:
DiceClass(){
srand(time(0));
}
int firstdiceroll = 2+rand()%11;
void PhaseOne(){
cout << "Lets play some craps. n" << endl;
system("pause");
cout << endl;
cout << "You rolled " << firstdiceroll << "." << endl;
if(firstdiceroll==7 || firstdiceroll==11){
cout << "You win!!" << endl;
wins++;
cout << "Currents wins: " << wins << "nCurrent loses: " << loses << endl;
again();
}
else if(firstdiceroll==2 || firstdiceroll==3 || firstdiceroll==12){
cout << "You lose!" << endl;
loses++;
cout << "Currents wins: " << wins << "nCurrent loses: " << loses << endl;
again();
}
else{
cout << "Rolling again!n" << endl;
system("pause");
cout << endl;
PhaseTwo();
}
} //ends PhaseOne
void PhaseTwo(){
int seconddiceroll = 2+rand()%11;
cout << "You rolled " << seconddiceroll << endl;
if(firstdiceroll==seconddiceroll){
cout << "You win!!" << endl;
wins++;
cout << "Currents wins: " << wins << "nCurrent loses: " << loses << endl;
again();
}
else if(seconddiceroll==7){
cout << "You lose!" << endl;
loses++;
cout << "Currents wins: " << wins << "nCurrent loses: " << loses << endl;
again();
}
else{
cout << "Rolling again." << endl;
system("pause");
cout << endl;
PhaseTwo();
}
} //ends PhaseTwo
}; //ends DiceClass
int main()
{
DiceClass DObject1;
DObject1.PhaseOne();
return 0;
}
class DiceClass{
public:
DiceClass(){
srand(time(0));
}
int firstdiceroll = 2+rand()%11;
// etc.
};
类的成员变量在进入构造函数体之前被初始化。因此,在更改随机数序列之前设置firstdiceroll
。
相关文章:
- 如何为我的容器实现随机访问迭代器?
- 为什么我的 2d 数组的第二行从 RAM 中获取随机值?
- 我的求解(字符串 a、字符串 b)的输出与随机哈希中的预期输出不匹配
- 为什么我的数组值会更新为随机值?
- 我的随机生成器是否不工作,或者我决定人/骨架是否击中对手的方式是否有错误
- 遍历我的数据结构,并向其中输入随机值
- 为什么我的函数名称中会随机出现一个额外的字母
- 我的控制台正在打印随机单词以及没有执行正确的数学运算
- 浏览器将随机HTTP消息正文发送到我的boost.asio服务器.我可以更改此设置吗?
- 随机字符串生成器不编辑我的字符串数组 (C++)
- 编译器将随机字符添加到我的 char 数组中
- 我如何在一串随机生成的字母I C 中查找一个单词
- 为什么数据中的随机部分替换了曾经存储在我的角色数组中的其他数据
- 为什么我的合并排序最终将随机4放置
- 为什么我随机生成的数组只输出零
- 在我的库中随机未定义的参考
- MPI随机漫步:为什么我的消息会丢失
- C++时间()给我的结果几乎是随机的
- 为什么我的TicTacToe游戏在生成随机移动时会卡住
- 无论用户输入,我的数组都会接受随机值