C ++函数不会返回值

时间:2016-05-02 05:07:18

标签: c++ function debugging

#include<iostream>
#include<cstdlib>
#include<string>
#include<time.h>
using namespace std;

//Functions
// player strategy
int strategy(int user1Strat, int user2Strat);
// player total score per round
int currentScore();
// Display game result
void printResults();

int main()
{
    int total_player1 = 0; // player 1 current score
    int total_player2 = 0; // player 2 current score
    int player1_strat= 0;  //player 1 strategy for each turn
    int player2_strat = 0; // player 2 strategy for each turn

    // seed the random number generator.
    srand(static_cast<int> (time(NULL)));

    // get strategy for each player using functions <strategy>

    strategy(player1_strat, player2_strat);

    cout << player1_strat << endl << player2_strat << endl;

    system("pause");
    return 0;
}

int strategy(int user1Strat, int user2Strat)
{
    int x,
        y;

    cout << "Enter player1's roll until strategy: ";
    cin >> user1Strat;
    cout << "Enter player2's roll until strategy: ";
    cin >> user2Strat;
    x = user1Strat;
    y = user2Strat;

    return x, y;
}

在函数strategy中调用函数main时,它将执行它应该如何执行,但是一旦我要求返回它将返回的值

Enter player1's roll until strategy: 10
Enter player2's roll until strategy: 5

0
0

press any key to contiue...

有人知道为什么会发生这种情况或导致它的原因,是我在策略功能中的错误吗?或者在打电话给它?

2 个答案:

答案 0 :(得分:1)

收到输入后,strategy(player1_strat, player2_strat);中的{p> main()无效,因此您无法看到player1_stratplayer2_strat上的任何更改。

如果您要修改player1_strat中的player2_stratstrategy,可以通过引用来执行此操作:

void strategy(int& user1Strat, int& user2Strat)
{
    cout << "Enter player1's roll until strategy: ";
    cin >> user1Strat;
    cout << "Enter player2's roll until strategy: ";
    cin >> user2Strat;
}

或者你可以返回&#34;多重值&#34;使用std::pair

//#include <utility>
std::pair<int, int> strategy(int user1Strat, int user2Strat)
{
    int x, y;

    cout << "Enter player1's roll until strategy: ";
    cin >> user1Strat;
    cout << "Enter player2's roll until strategy: ";
    cin >> user2Strat;
    x = user1Strat;
    y = user2Strat;

    return std::make_pair(x, y);
}

//main()
std::pair<int, int> result = strategy(player1_strat, player2_strat);

x = result.first;
y = result.second;

答案 1 :(得分:0)

您只能从函数返回单个对象。 return x, y;不会返回xy,只返回y。如果要更新多个变量,请将它们作为引用提供给函数,并在函数内更改它们的值。

编辑:

正如@Keith Thompson在评论中提到的,逗号实际上是本声明中的运算符。它评估x(在那里做的不多),丢弃结果然后评估并返回第二个参数y

相关问题