我无法从此功能获得正确的回报

时间:2015-04-27 02:27:43

标签: c++

我正在制作一个tic tac toe程序。我有不同的功能来测试不同的可能结果。当我测试我的对角线可能性时,它可以正常工作。但是,当我尝试测试行或列时,它总是返回0.我认为这是因为我的return语句和break语句位于错误的位置,但我无法找到正确的位置。

<div class="container" id="content">
    <form>        
    <div class="row">
        <div class="col-md-2">Label
            <input value="nonnested input">
        </div>
        <div class="col-md-2">Label
            <input value="nonnested input">
        </div>
    </div>
    <br/>
    <div class="row">
        <div class="form-group col-md-4">
            Label across two inputs, Label across two inputs
            <div class="row">
                <div class="col-md-2">
                    <input value="nested input 1" >
                </div>
                <div class="col-md-2">
                    <input value="nested input 2" >
                </div>
            </div>
        </div>
        </div>
    </form>
</div>

3 个答案:

答案 0 :(得分:1)

两件事;你需要在循环之外移动return 0。否则,你将永远无法测试所有可能性。其次,输出语句在return之后,因此无法访问。

答案 1 :(得分:0)

break后你不需要return语句。函数中的最后一次返回似乎是函数的错误状态,因此您可以将其保持在循环之外。第一个if分支的输出声明应该在您返回之前。

int testCol (int board[3][3]){//test cols for win
    int b = 0;
    int c = 0;
    for (b = 0; b < 3; b++){
        if (board[0][b] == 1 && board[1][b] == 1 && board[2][b] == 1){//test player 1

             cout << "I work" << endl;
             return 1;

        }
        else if(board[0][b] == 2 && board[1][b] == 2 && board[2][b] == 2){//test player 2
             return 2;            
        }

    }
    return 0;
}

答案 2 :(得分:0)

当您找到完整列时,您会提早返回。如果没有获胜者,则在测试所有列后返回0。

这里是固定版本。

int testCol (int board[3][3]){//test cols for win
    for (int b = 0; b < 3; b++){
        if (board[0][b] == 1 && board[1][b] == 1 && board[2][b] == 1){//test player 1
             return 1;
        }
        else if(board[0][b] == 2 && board[1][b] == 2 && board[2][b] == 2){//test player 2
             return 2;
        }
    }
    return 0;
}