因此,我一直在自学如何编写 C++ 代码,我购买了迈克尔道森 (Michael Dawson) 撰写的 Beginning C++ through game programming,第三版 一书,其中有一章介绍了循环。在本章的末尾,您制作了一个混淆单词的游戏。我想更进一步,并随机选择了 5 个单词。但问题是,它总是获得 5 的值,因此总是选择第五个单词。
下面代码如下
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
enum fields {WORD, HINT, NUM_FIELDS};
const int NUM_WORDS = 5;
const string WORDS[NUM_WORDS][NUM_FIELDS] =
{
{"wall", "Do you feel you're banging your head against something?"},
{"glasses", "These might help you see the answer"},
{"labored", "Going slowly is it?"},
{"persistent", "Keep at it"},
{"jumble", "It's what this game is about!"}
};
srand(time(0));
int preWord = rand() % 3;
string tempWord;
string theWord = WORDS[preWord][WORD]; //word to guess
string theHint = WORDS[preWord][HINT]; //hint for word
if (preWord = 1)
{
theWord = "wall";
tempWord = "wall";
}
if (preWord = 2)
{
theWord = "glasses";
tempWord = "glasses";
}
if (preWord = 3)
{
theWord = "labored";
tempWord = "labored";
}
if (preWord = 4)
{
theWord = "persistent";
tempWord = "persistent";
}
if (preWord = 5)
{
theWord = "jumble";
tempWord = "jumble";
}
int length = theWord.size();
for (int i = 0; i < length; ++i)
{
int index1 = (rand() % length);
int index2 = (rand() % length);
char temp = theWord[index1];
theWord[index1] = theWord[index2];
theWord[index2] = temp;
}
cout << "\t\t\tWelcome to the Word Jumble!\n\n";
cout << "Unscramble the letters to make a word.\n";
cout << "Enter 'hint' for a hint.\n";
cout << "Enter 'quit' to quit the game.\n\n";
cout << "The word is: " << theWord;
cout << "\nvariable 'preWord' is: " << preWord;
string guess;
cout << "\n\nYour guess: ";
cin >> guess;
while ((guess != tempWord) && (guess != "quit"))
{
if (guess == "hint")
{
cout << theHint;
}
else
{
cout << "Sorry, that's not it.";
}
cout <<"\n\nYour guess: ";
cin >> guess;
}
if (guess == tempWord)
{
cout << "\nThat's it! You guessed it!\n";
}
cout << "\nThanks for playing!\n";
return 0;
}
最佳答案
在你的条件下,你应该写:
if (preWord == x)
这是一个比较,而不是
if (preWord = 5)
这是一个赋值 - 这意味着,当您的代码到达每个 if
语句时,它实际上会将值分配给您的变量 - 从您的第 5 个案例开始如果是最后一个,它最终会将 preWord
的值更改为 5
。
关于c++ - 什么应该是一个随机变量总是生成 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16704308/