如何使用其他函数中的变量

时间:2021-05-27 09:34:08

标签: c++

int calculateX()
{
    
    int x;
    cout<<"Enter value for x: ";
    cin>>x;
    return x;
}

int anotherFunction()
{
    /////
}

int main()
{
    calculateX();
    anotherFunction();
    
    return 0;
    
}
    

这是一个代码示例。我如何才能将用户在 calculateX() 函数中的输入用于 anotherFunction() 函数?

4 个答案:

答案 0 :(得分:5)

你必须使用函数参数:

int calculateX()
{    
    int x;
    cout<<"Enter value for x: ";
    cin>>x;
    return x;
}

int anotherFunction(int x)
{
    /////
}

int main()
{
    int x = calculateX();
    anotherFunction(x);
    
    return 0;    
}

答案 1 :(得分:0)

你需要的是一个已经回答的按值传递或一个像这样的全局变量

#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int anotherFunction()
    {
        cout << g;
    }
int main () {
   // Local variable declaration:
   int a, b;
   a = 10;
   b = 20;
   g = a + b;
   anotherFunction();
   return 0;
}

一个全局变量可以被任何函数访问。也就是说,全局变量在声明后可在整个程序中使用。

答案 2 :(得分:0)

必须声明变量 x global(在 calculateX() 函数之外),以便 anotherFunction() 可以看到它。如果在calculateX()函数内部定义了变量x,退出函数后会被删除。

int x;
int calculateX()
{   
    cout<<"Enter value for x: ";
    cin >> x;
    return x;
}

int anotherFunction()
{
    /////
}

int main()
{
    calculateX();
    anotherFunction();
    return 0;
    
}

答案 3 :(得分:0)

函数通常在其名称之前具有返回类型。例如:

int calculateX() {   
    int x;
    cout<<"Enter value for x: ";
    cin>>x;   
    anotherFunction(x)
    return x;
}

int 是这里的返回类型。您正在从主函数调用两个函数。 calculateX 有一个名为 x 的 int 类型变量。因此,您无法从 calculateX 范围之外访问 x。但是您可以将它返回到您的主函数并将其存储在不同的变量中,以便它在主函数中可用。一旦它变得可用,您就可以将其作为参数发送给另一个函数。在你的情况下它应该是这样的:

int anotherFunction(int valueFromMain)
{
   std::cout << valueFromMain << std::endl;
}

int main(){
    int returnedFromCalculateX = calculateX(); //You have returned value available on main Function
    anotherFunction(returnedFromCalculateX); //Send It to anotherFunction(pass by value)
    return 0;    
}

您也可以发送该值作为参考。这需要更高的理解。请检查:https://www.w3schools.com/cpp/cpp_function_reference.asp 了解更多详情。

相关问题