Search code examples
c++returnvoid

Changing Void function to Return Value function


Given a currently functioning program using a void function: Change the program so the void function does not output the value of a variable but sends to the main function.

void trackVar(double& x, double y);

int main()
{
    double one, two;

    cout << fixed << showpoint << setprecision(2);
    cout << "Enter two numbers: ";
    cin >> one >> two;
    cout << endl;

    trackVar(one, two);
    cout << "one = " << one << ", two = " << two << endl;

    trackVar(two, one);
    cout << "one = " << one << ", two = " << two << endl;

    return 0;
}
void trackVar(double& x, double y)
{
    double z;
    z = floor(x) + ceil(y);
    x = x + z;
    y = y - z;

    cout << "z = " << z << ", ";
}

I can get so the output lists the values for one and two correctly, but do not know how to have output for 'z' as part of the main function.

Final result (for those interested):

double trackVar(double& x, double y); ///function prototype (switched to double instead of void)

int main()
{
    double one, two, z;

    cout << fixed << showpoint << setprecision(2);
    cout << "Enter two numbers: ";
    cin >> one >> two;
    cout << endl;

z = trackVar(one,two);
    cout <<"z= "<<z<<" "<<"one= "<<
    one<<"two= "<<two<< endl;
z = trackVar(two,one);
    cout <<"z= "<<z<<" "<<"one= "<<
    one<<"two= "<<two<< endl;

    return 0;
}

double trackVar(double& x, double y)
{
    double z;
    z = floor(x) + ceil(y);
    x = x + z;
    y = y - z;

    return z;
}

Solution

  • After checking, I update my post.

    try this:

    void trackVar(double& x, double& y)
    {
        double z;
        z = floor(x) + ceil(y);
        x = x + z;
        y = y - z;
    }
    

    So, the normal functiontrackVar(double x, double y) it will sent a copy x and y into the function, so even you chang them in there, nothing changes. But, if you using reference,trackVar(double& x, double& y), to change x and y there, it will really change the value, so be careful using reference.

    for a simple example:

    void trackVar(double& a, double& b)
    {
         a = 99;
         b = 66;
    }
    
    int main()
    {
        double a = 1;
        double b = 2;
    
        trackVar(a, b);
        std::cout << "New a: "<< a << std::endl;
        std::cout << "New b: " << b << std::endl;
        return 0;  
    }
    

    output: New a: 99 output: New b: 66