***問題已得到解答,問題的癥結在於 「使用C++編程原則和實踐」一書中的錯誤,其中srand可接受與頭文件中定義的函數randint()一起使用。爲什麼不是srand種子改變結果?
我希望答案不太明顯,但我環顧四周,似乎無法弄清楚爲什麼srand不會改變bull_pen向量中的值。每次運行我都會得到相同的4個整數。
我已經讀過關於使用計算機時鐘的所有信息,確保只在循環等或包含stdlib.h之外使用srand,但這些都不會有幫助。 使用用戶輸入作爲種子看起來很容易,但現在我覺得我在某處丟失了一些基本理解 。 如果我有不好的風格等,我會提前道歉 - 對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));'爲了讓它每次運行它,以便它產生不同的序列。 –