C++函数不会返回值
C++ functions won't return values
#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...
有谁知道为什么会发生这种情况或是什么原因造成的,是我在策略函数中的错误吗?还是打电话?
>main()
strategy(player1_strat, player2_strat);
在收到输入后不执行任何操作,因此您不会看到player1_strat
和player2_strat
的任何更改。
如果你想修改player1_strat
和player2_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;
不会返回x
和y
,而只会返回y
。如果要更新多个变量,请将它们作为引用提供给函数,并在函数中更改它们的值。
编辑:
正如@Keith Thompson在评论中提到的,逗号实际上是本语句中的运算符。它计算x
(那里没有太多事情要做(,丢弃结果,然后计算并返回第二个参数y
。
相关文章:
- 从python中调用C++函数并获取返回值
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 程序不向函数返回值
- 如何在另一个函数中使用返回值作为参数?
- 编写以 C++ 为单位返回值的函数
- 了解在返回值之前和之后使用 EAX 的函数调用
- 当我使用 void 函数的返回值(通过强制转换函数指针)时,究竟会发生什么?
- 如何在不使用临时变量的情况下取消引用返回指针的函数的返回值?
- 如何将不可移动和不可复制的函数返回值获取到数组中
- G++ 编译器是否在未使用返回值的情况下将 constexpr 函数视为常规函数?
- 为什么当你将函数的返回值乘以零时它不会短路?
- 函数的返回值类型是别名 ***或 *** 布尔值
- 如何在没有返回值的情况下使用(特征)unaryExpr 和 lambda 函数?
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 为什么这个"ctypes"包装函数的返回值是"c_long(0)"而不是&quo
- 函数不显示返回值 - C++
- 结构新手,我对如何从 void 函数中返回值并将其放入另一个函数感到困惑
- 将 void 函数更改为返回值函数
- 返回值函数中结构成员赋值的额外拷贝