You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将无返回值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 trackVar from void to double so it can send the z value back to main().
  • Modified Prototype: The function declaration now matches the new return type to avoid compiler errors.
  • Capture Return Value: Added a double z in main() to store the value returned by each call to trackVar.
  • Moved Output to Main: Removed the cout inside trackVar—now all printing happens in main(), keeping the function focused on calculation rather than I/O.
  • Pass-by-Value Note: The y parameter is passed by value, so modifying it inside trackVar doesn't change the original variable in main()—this preserves your original program's behavior for y.

内容的提问来源于stack exchange,提问作者Ian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:16:56