如何在C ++中的另一个函数中使用局部变量?

时间:2017-05-10 02:27:07

标签: c++

如何在另一个函数treasureX中使用局部变量win?在win函数中,该程序使用board[6][t]但不使用treasureXtreasureX变量是全局变量,但代码未按预期工作。

#include <iostream>
#include <random>
#include <ctime>

char board[8][8];
char treasureX;
int t;

void Board() {
    for (int x = 1; x < 7; x++) {
        for (int y = 1; y < 7; y++) {
            board[x][y] = '.';
        }
    }
}


void treasureSpawn() {
    t = rand() % 6 + 1;
    board[6][t] = 'X';
    treasureX = board[6][t];
}

int displayBoard() {
    for (int x = 0; x<8; x++) {
        for (int y = 0; y<8; y++) {
            std::cout << board[x][y];
            if (y == 7) {
                std::cout << std::endl;
            }
        }
    }
    return 0;
}

char playerPosition;

char playerSpawn() {
    int randomY;
    randomY = rand() % 6 + 1; 
    board[1][randomY] = 'G';
    playerPosition = board[1][randomY];
    return playerPosition;
}

int movement() {
    char move;
    std::cout << "Use WASD keys to move." << std::endl;
    std::cin >> move;
    for (int x = 1; x<7; x++) {
        for (int y = 0; y<8; y++) {
            if (board[x][y] == 'G') {
                board[x][y] = '.';
                if (move == 'W' || move == 'w') {
                    return board[x - 1][y] = 'G';
                }
                else if (move == 'A' || move == 'a') {
                    return board[x][y - 1] = 'G';
                }
                else if (move == 'D' || move == 'd') {
                    return board[x][y + 1] = 'G';
                }
                else if (move == 'S' || move == 's') {
                    return board[x + 1][y] = 'G';
                }
                else {
                    std::cout << "Wrong key!" << std::endl;
                    movement();
                }
            }
        }
    }
    return 0;
}

int win() {
    if (treasureX == 'G') { // when player arrives at 'X' this function does not execute. Works if I put 'board[6][t]' instead of 'treasureX'.
        std::cout << "You win" << std::endl;
        return 0;
    }
}

int main() {
    srand(time(0));
    Board();
    playerSpawn();
    outOfBounds();
    treasureSpawn();
    displayBoard();
    do {
        movement();
        checkIf();
        displayBoard();
    } while (win() != 0);
}

2 个答案:

答案 0 :(得分:0)

此处,TreasureX是函数void treasureSpawn()中未初始化的变量,其值在整个程序中不会更改(并始终为'X')。 但是,board[6][t]在程序执行时更改,更准确地说是在int movement()函数中,因此当程序执行函数win()时它们的值不同

答案 1 :(得分:0)

将treasureX的定义更改为const char & treasureX = treasureSpawn();并将treasureSpawn更改为

const char & treasureSpawn() {
    t = rand() % 6 + 1;
    board[6][t] = 'X';
    return board[6][t];
}

然后当玩家移动时,treasureX的值会改变