为什么randomize()函数不起作用?

时间:2014-12-30 09:16:12

标签: c++ random

我和我的朋友正试图制作一个" Hangman"我们学校项目使用C ++的游戏。但是在编译时,消息显示在此范围内未声明标准函数randomize()和random。代码有什么问题?

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;
const int MAXLENGTH=80;
const int MAX_TRIES=5;
const int MAXROW=7;

int letterFill (char guess, char secretword[], char guessword[]) {
    int matches = 0;
    for (int i = 0; secretword[i]!='\0'; i++) {
        if (guess == guessword[i])
            return 0;
        if (guess == secretword[i]) {
            guessword[i] = guess;
            matches++;
        }
    }
    return matches;
}

void initUnknown (char word[], char unknown[]) {
    int i, length = strlen(word);
    for (i = 0; i < length; i++)
        unknown[i]='*';
    unknown[i]='\0';
}

int main () {
    char unknown [MAXLENGTH];
    char letter;
    int wrong_guesses=0;
    char word[MAXLENGTH];
    char words[][MAXLENGTH] = { "batman begins", "superman returns", "2012",
        "tarzan", "goal", "300", "space jam", "transformers", "megamind",
        "spiderman" };
    randomize();
    int n=random(10);
    strcpy(word,words[n]);
    initUnknown(word, unknown);

    cout << "\n\nWelcome to hangman...Guess a Movie Name";
    cout << "\n\nEach letter is represented by a star.";
    cout << "\n\nYou have to type only one letter in one try";
    cout << "\n\nYou have " << MAX_TRIES << " tries to try and guess the word.";
    cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";

    while (wrong_guesses < MAX_TRIES) {
        cout << "\n\n" << unknown;
        cout << "\n\nGuess a letter: ";
        cin >> letter;
        if (!letterFill(letter, word, unknown)) {
            cout << endl << "Whoops! That letter isn't in there!" << endl;
            wrong_guesses++;
        } else
            cout << endl << "You found a letter! Isn't that exciting!" << endl;

        cout << "You have " << MAX_TRIES - wrong_guesses;
        cout << " guesses left." << endl;
        if (!strcmp(word, unknown)) {
            cout << word << endl;
            cout << "Yeah! You got it!";
            break;
        }
    }
    if(wrong_guesses == MAX_TRIES) {
        cout << "\nSorry, you lose...you've been hanged." << endl;
        cout << "The word was : " << word << endl;
    }
    cin.get();
}

2 个答案:

答案 0 :(得分:0)

在C ++或C中,您可以使用rand生成随机数。您可以在http://www.cplusplus.com/reference/cstdlib/rand/

查看更多信息

定期!

答案 1 :(得分:0)

使用 srand() 为 rand() 设置种子。

    #include <cstdlib>
    #include <cstddef>
    #include <ctime>
    ...

    int main(...){
        ...
        srand(time(NULL));

        int randomByte = rand()%256;
        ...
    }