#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...
有人知道为什么会发生这种情况或导致它的原因,是我在策略功能中的错误吗?或者在打电话给它?
答案 0 :(得分:1)
strategy(player1_strat, player2_strat);
中的{p> main()
无效,因此您无法看到player1_strat
和player2_strat
上的任何更改。
如果您要修改player1_strat
中的player2_strat
和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;
}
或者你可以返回&#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;
不会返回x
和y
,只返回y
。如果要更新多个变量,请将它们作为引用提供给函数,并在函数内更改它们的值。
编辑:
正如@Keith Thompson在评论中提到的,逗号实际上是本声明中的运算符。它评估x
(在那里做的不多),丢弃结果然后评估并返回第二个参数y
。