将无返回值void函数改造为带返回值函数并在main中输出变量z
Capture a Local Variable from a Void Function to Use in Main (C++)
Got it, let's work through this. You originally had a void function trackVar that calculated a local variable z and printed it directly. But you wanted to let main() handle the output instead, which meant you needed to pass that z value back to main() instead of printing it inside the function. Here's how to refactor your code correctly:
Original Code
#include <iostream> #include <cmath> #include <iomanip> using namespace std; 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 << ", "; }
Refactored Code (With z Returned to Main)
#include <iostream> #include <cmath> #include <iomanip> using namespace std; double trackVar(double& x, double y); // Updated prototype to return double int main() { double one, two, z; // Added z variable to capture returned value cout << fixed << showpoint << setprecision(2); cout << "Enter two numbers: "; cin >> one >> two; cout << endl; z = trackVar(one, two); // Assign returned z to our main variable cout << "z = " << z << ", one = " << one << ", two = " << two << endl; z = trackVar(two, one); // Capture z again for the second call 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; // Note: y is passed by value, so modifying it here doesn't affect main's variables y = y - z; return z; // Return z to the caller (main) }
Key Changes Explained
- Updated Return Type: Changed
trackVarfromvoidtodoubleso it can send thezvalue back tomain(). - Modified Prototype: The function declaration now matches the new return type to avoid compiler errors.
- Capture Return Value: Added a
double zinmain()to store the value returned by each call totrackVar. - Moved Output to Main: Removed the
coutinsidetrackVar—now all printing happens inmain(), keeping the function focused on calculation rather than I/O. - Pass-by-Value Note: The
yparameter is passed by value, so modifying it insidetrackVardoesn't change the original variable inmain()—this preserves your original program's behavior fory.
内容的提问来源于stack exchange,提问作者Ian
相关产品推荐
相关产品推荐

