简体   繁体   中英

How do I pass multiple values in a function to different functions in C++?

For my C++ program, I need to use 3 functions to ask user to input mass, accleration, and displacement, calculate force and work with those inputs in a diff function, then output force and work in the 3rd function.

My problem is that Im having trouble passing the values for mass, accleration, and displacement from the first function to the 2nd so that I can calculate force and work..Here's my code so far


using namespace std;

string userName;
int amounts(float, float, float); //function prototype
int calcForceAndWork(float, float); //function prototype

;

int main()
{

    float mass, accleration, displacement;


    string userName;
    cout << "Hello user, what is your name?" << endl;
    cin >> userName;
    amounts(mass, accleration, displacement);

    cout << "Enter the mass value: " << endl;
    cin >> mass;
    cout << "Enter the displacement value: " << endl;
    cin >> displacement;
    cout << "Enter the accleration value: " << endl;
    cin >> accleration; 

    return 0;

}
int calcForceAndWork(float, float)
{
    amounts(mass, accleration, displacement);
    calcForceAndWork(force, work);
    double force, work;

    force = mass*accleration;
    work = force*displacement;

    return 0;
}

These are my first 2 functions. How do I pass the values of mass, accleration, and force from my first function to the 2nd function?

I'm afraid you need to learn about the absolute raw basics of functions, return values, passing by value vs passing by reference, etc. still...

Let's keep it really simple. Just use "pass by value", and return a result. Here's an example:

int getSum( int a, int b )
{
    return a + b;
}

int main()
{
    int myValue1 = 1, myValue2 = 2;
    int mySum = getSum( myValue1, myValue2 );

    return 0; //this is returned to the OS. 0 == no error, i.e. success
}

Function main calls function getSum. It passes the values stored in the variables called myValue1 and myValue2 to that function. Function getSum receives those values into variables called a and b. It adds them together and returns the value. That return value is stored in the mySum variable in function main. If you wanted, you could then pass that mySum value on to another function.

At the end of function main, it returns 0. That is a "special" return. main is the entry point function for the operating system into your program. By convention, you return 0 to the OS to indicate success. Any other number returned to the OS is considered an "error code".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM