【发布时间】:2015-07-11 21:21:18
【问题描述】:
我希望答案不会太明显,但我环顾四周,似乎无法弄清楚为什么 srand 没有改变 Bull_pen 向量中的值。 每次运行时,我都会得到相同的 4 个整数。
我已经阅读了所有关于使用计算机时钟的信息,确保只使用 srand 一次或在循环之外等,包括 stdlib.h,但这些都没有帮助。 使用用户输入作为种子似乎很容易,但现在我觉得我错过了一些 某处的基本了解。 如果我的风格很差等,我提前道歉——对于 C++ 和一般编程来说都是新手。感谢您的帮助。
#include "..\..\std_lib_facilities.h"
int main()
{
int seed;
cout << "Before the game begins, enter any integer.\nThis will generate a seed to randomize the game: ";
cin >> seed;
srand(seed);
cout << "I have four numbers in a sequence for you to guess." << endl
<< "For every digit you guess that matches a digit in my sequence, I will tell you\nthat you guessed that many 'cows'." << endl
<< "For ever digit you guess that matches a digit AS WELL as matches the digits\nlocation in my sequence, I will say you guessed" << endl
<< "that many 'bulls'. Guessing all four 'bulls' wins the game.\n";
while (1 == 1){
vector<int>bull_pen(4);
bull_pen[0] = randint(9);
bull_pen[1] = randint(9);
bull_pen[2] = randint(9);
bull_pen[3] = randint(9);
vector<int>guesses(4);
int guess;
int found = 0;
int bulls = 0;
int cows = 0;
while (found != 1){
vector<int>bull_pen_flags(4);
cout << "Please enter your guesses: ";
for (int i = 0; i < guesses.size(); i++){
cin >> guess;
guesses[i] = guess;
}
for (int i = 0; i < bull_pen.size(); i++){
if (bull_pen[i] == guesses[i]) { bulls++; bull_pen_flags[i] = 1; }
}
if (bulls < 4){
for (int guess_index = 0; guess_index < guesses.size(); guess_index++){
for (int bull_index = 0; bull_index < bull_pen.size(); bull_index++){
if (guess_index != bull_index && bull_pen_flags[bull_index] != 1){
if (guesses[guess_index] == bull_pen[bull_index]) {
cows++;
bull_pen_flags[bull_index] = 1;
}
}
}
}
if (cows > 0) cout << cows << " cow(s).\n";
else cout << "No cows.\n";
if (bulls > 0) cout << bulls << " bull(s).\n";
else cout << "No bulls.\n";
bulls = 0;
cows = 0;
}
else found = 1;
}
cout << "You've guessed all four bulls; " << bull_pen[0] << bull_pen[1] << bull_pen[2] << bull_pen[3] << "\nYou win!\n";
}
}
【问题讨论】:
-
什么是
randint?它是如何定义的? -
不知道。它可能来自我正在使用的头文件,我从一本用于学习 C++ 的书中获取。有没有更通用的选择?我见过 rand 的用法,所以我觉得用 rand 替换 randint 会有帮助吗?
-
如果您输入相同的
seed,那么rand()每次都会产生相同的序列。这就是 rand() 的定义方式。通常,您会使用srand(time(0));来播种,以便每次运行它时,它都会产生不同的序列。 -
不管种子的不同输入我得到相同的结果,我也尝试过 srand(time(NULL)) 并根据您的建议 srand(time(0)) 并且仍然是相同的结果 -在这里挠头..
-
我想您正在关注 Bjarne Stroustrup 的“使用 C++ 进行编程原理和实践”?