如何返回一个变量,以便在C++中的另一个函数中使用它
How do I return a variable so I can use it in another function in C++?
这是一个愚蠢的问题,但老实说,我无法在我的程序中使用它。我刚开始使用C++,但我一直在做错事。我让用户输入"pile"的值,然后我想转到我的第二个函数,将pile除以二。我的教授说我不允许使用全局变量。这是我的代码:
int playerTurn();
int main() //first function
{
int pile = 0;
while ( pile < 10 || pile > 100 ) {
cout << "How many marbles would you like there to be?" << endl;
cout << "Please choose between 10 and 100: ";
cin >> pile;
}
return pile; //the variable I'm trying to return is pile
playerTurn();
}
int playerTurn(pile) //second function
{
int limit = pile / 2; //says pile is an undeclared identifier
}
我似乎无法将"堆"转移到我的另一个函数playerTurn
return
语句退出一个函数,并将一个值返回到调用它的位置。
因此,您的代码所做的就是退出main()
并将堆返回给操作系统。
您需要调用playerTurn,使用pile作为参数。
return
语句立即从当前函数返回。因此,当您在main
函数中使用它时,它会从main
函数返回。
要将变量传递给另一个函数,请将其作为参数传递:
playerTurn(pile);
此外,当您声明一个接受参数的函数时,您必须完全指定参数,就像您声明其他变量一样:
void playerTurn(int pile)
{
// ... your implementation here...
}
如果你在理解传递参数或返回值时遇到困难,那么你应该继续阅读基础知识,直到你理解为止
检查描述的注释
int playerTurn(); // Function declaration
int main() //first function
{
int pile; // Define variable before usage
do // Google do-while loops.
{
cout << "How many marbles would you like there to be?" << endl;
cout << "Please choose between 10 and 100: ";
cin >> pile;
}while ( pile < 10 || pile > 100 );
// Calling the secondary function and passing it a parameter
// and then getting the result and storing it in pile again.
pile = playerTurn(pile)
}
// Not really sure what you are trying to do here but
// assuming that you want to pass pile to this function
// and then get the return type in main
int playerTurn(int pile)
{
int limit = pile / 2; //Processing.
return limit; // Return from inside the function, this value goes to pile in main()
}
您对
playerTurn
的正向定义与实现不匹配。您需要将其更改为int playerTurn(int pile)
。playerTurn
的实现没有指定参数类型(即int
)。据我所见,您正试图从
main
返回pile
。这实际上会退出您的程序。相反,你似乎想把它当作一个论点。要做到这一点,只需将其放在括号内即可(当然,去掉return xyz;
行)。
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 运行同一解决方案的另一个项目的项目
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- C++从另一个类访问公共静态向量的正确方法是什么
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 使用std::transform将一个范围的元素添加到另一个范围中
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 我可以将一个用clang c++11编译的对象与另一个用c++17编译的对象链接起来吗
- 修改函数中的指针(将另一个指针作为参数传递)
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- C++试图读取一个文件并输出到另一个文本文件
- 如何将指针从一个void函数传递到另一个C++
- 如何从另一个文件继承私有成员变量和公共函数
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 如何在C++中将函数发送到另一个进程
- 如何通过按下第三个窗口中的按钮,将QString从一个窗口获取到另一个窗口