什么应该是一个随机变量总是生成5

Yan*_*ros 0 c++ visual-c++

所以我一直在教我自己如何编写C++代码我通过游戏编程购买了Beginning C++这本书,Michael Dawson 编写了第三版,并且它是你学习循环的一章.在本章的最后,你制作了一个混乱的游戏.我想进一步使用它并随机选择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;
}
Run Code Online (Sandbox Code Playgroud)

Nbr*_*r44 5

在你的条件下,你应该写:

if (preWord == x)

这是一个比较,而不是

if (preWord = 5)

这是一个赋值 - 这意味着,当你的代码到达每个if语句时,它实际上会将值赋值给你的变量 - 并且从你的第五个案例开始,它最终会改变preWordto 的值5.