So I am in a intro class for computer programming. I am not very good at working with multiple functions in a script. I was given this task this week relating to the code below.
"Rewrite the function trackVar so that rather than printing the value of z it sends its values back to the calling environment (main() function) and the calling environment prints the values of z.
Please write comments throughout the program to illustrate your understanding."
Below is the code in question. I have tried several attempts to do what I think is being asked of me to no avail. Including changing the function so it returns an output. Any input is greatly appreciated!
"Rewrite the function trackVar so that rather than printing the value of z it sends1 its values back to the calling environment (main() function) and the calling environment prints the values of z.
1. Meaning returns the value.
From jonnin's example this would be: double trackVar(double& x, double y) for the function definition and the prototype would also have to change.
#include <iostream>
#include <cmath>
#include <iomanip>
usingnamespace std;
double trackVar(double& x, double y); // < -- handy andy points out now a double return type.
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;
// the function trackVar now will return a double so you can use it as a variable like below
cout << "trackVar = " << trackVar(one, two) << endl;
return 0;
}
double trackVar(double& x, double y) // like others have said the return value is now a "double" type instead of a "void"
{
double z;
z = floor(x) + ceil(y);
x = x + z;
y = y - z;
// cout << "z = " << z << ", "; <-- Remove this as they want to you print from the main function
// replace this removed code with the following
return z; // This will send the value of z out of the function and back to the place where you made the function call.
}