C++函数不会返回值

C++ functions won't return values

本文关键字:返回值 函数 C++      更新时间:2023-10-16
#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;
}

在函数中调用函数strategymain它将按应有的方式执行,但是一旦我要求返回值,它只会返回

Enter player1's roll until strategy: 10
Enter player2's roll until strategy: 5
0
0
press any key to contiue...

有谁知道为什么会发生这种情况或是什么原因造成的,是我在策略函数中的错误吗?还是打电话?

>main() strategy(player1_strat, player2_strat);在收到输入后不执行任何操作,因此您不会看到player1_stratplayer2_strat的任何更改。

如果你想修改player1_stratplayer2_strat in strategy ,你可以通过引用来做到这一点:

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

或者您可以使用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;

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

编辑:

正如@Keith Thompson在评论中提到的,逗号实际上是本语句中的运算符。它计算x(那里没有太多事情要做(,丢弃结果,然后计算并返回第二个参数y