Passing Variables Through Functions

Hello this is my first year taking C++ as an official class, and i am stuck on an assignment. Our teacher allowed us a break for the holiday season, however i really would like to keep programming. The next assignment is to run a program through several functions without using any global variables. Heres what i have:

//*******************************
// Mileage Program
// This program computes miles per gallon given four amounts
// for gallons used, and starting and ending values
//*******************************
#include

float flp1, flp2, flp3, flp4, strt_odo, end_odo, mpg;


void enter_gas()
{
cout << "Enter Fill Up One:
";
cin >> flp1;
cout << "Enter Fill Up Two:
";
cin >> flp2;
cout << "Enter Fill Up Three:
";
cin >> flp3;
cout << "Enter Fill Up Four:
";
cin >> flp4;

}

void enter_miles()
{
cout << "Enter Starting Odometer Value:
";
cin >> strt_odo;
cout << "Enter Ending Odometer Value:
";
cin >> end_odo;

}
void calc_miles()
{
mpg = (end_odo - strt_odo)/(flp1 + flp2 + flp3 + flp4);

}

void disp_mpg()
{
cout << "Miles Per Gallon is " << mpg;

}

int main()
{
enter_gas();
enter_miles();
calc_miles();
disp_mpg();
system("pause>nul");
}


but i am unsure how to change it so that there are no Global variables. Any help is much appreciated.

Comments

  • Probably what they want you to do is to define all the variables in the main function and then pass the variables to the functions through parameters and also references.

    For example, the parameters to the enter_gas function should be references to the four variables(flp1-flp4). Usually a function can return just one value, but with references as parameters, it can return all the four values.

    The calc_miles function could take the 6 values it needs as parameters and then return the result.

    I think if you read these two articles, then you will have a pretty good idea of how you can do all this:
    http://www.cplusplus.com/doc/tutorial/functions/
    http://www.cplusplus.com/doc/tutorial/pointers/
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion