如何返回一个变量,以便在C++中的另一个函数中使用它

How do I return a variable so I can use it in another function in C++?

本文关键字:C++ 另一个 函数 返回 何返回 变量 一个      更新时间:2023-10-16

这是一个愚蠢的问题,但老实说,我无法在我的程序中使用它。我刚开始使用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;行)。

相关文章: