函数未返回值问题:C++程序输入值无法传递至主函数
C++输入函数返回值异常问题解决
问题分析
你遇到的问题核心有两个:
- 参数传值调用的局限性:原代码中
mass和freqnat函数采用传值调用,函数内部的m和nf是main函数中变量的局部副本,修改副本不会影响原变量的值。 - 返回值未被接收:即便添加了
return m;和return nf;,main函数中没有将返回值赋值给对应的变量,导致attachedmass和naturalfrequency始终保持初始值0。
另外,最初函数未返回值时报错,是因为函数声明为double类型,必须返回对应类型的值,否则违反C++语法规则。
两种解决方法
方法1:利用函数返回值赋值
修改函数定义,去掉不必要的参数,在函数内部定义局部变量接收输入,返回该变量的值,main函数接收返回值并赋值给目标变量。
修正后的代码:
#include <iostream> #include <iomanip> using namespace std; void welcome(); double mass(); double freqnat(); int main() { double attachedmass = 0; double naturalfrequency = 0; welcome(); attachedmass = mass(); naturalfrequency = freqnat(); cout << attachedmass << setw(20) << naturalfrequency << endl; } void welcome() { cout << "Welcome to the spring stiffness program." << endl << endl << "This program calculates spring stiffness using mass and natural frequency to calculate your spring stiffness." << endl << endl; system("pause"); cout << endl; } double mass() { double m; cout << "Please enter your desired mass." << endl << endl; cin >> m; return m; } double freqnat() { double nf; cout << "Please enter your desired natural frequency." << endl << endl; cin >> nf; return nf; }
方法2:使用引用传递参数
将函数参数改为引用类型(double&),这样函数内部对参数的修改会直接作用到main函数中的原变量上,无需返回值。
修正后的代码:
#include <iostream> #include <iomanip> using namespace std; void welcome(); void mass(double& m); void freqnat(double& nf); int main() { double attachedmass = 0; double naturalfrequency = 0; welcome(); mass(attachedmass); freqnat(naturalfrequency); cout << attachedmass << setw(20) << naturalfrequency << endl; } void welcome() { cout << "Welcome to the spring stiffness program." << endl << endl << "This program calculates spring stiffness using mass and natural frequency to calculate your spring stiffness." << endl << endl; system("pause"); cout << endl; } void mass(double& m) { cout << "Please enter your desired mass." << endl << endl; cin >> m; } void freqnat(double& nf) { cout << "Please enter your desired natural frequency." << endl << endl; cin >> nf; }
关键说明
- 传值调用:函数接收变量的副本,修改副本不影响原变量,适合不需要修改原变量的场景。
- 引用传递:函数直接操作原变量的内存地址,修改会同步到原变量,适合需要从函数内部修改外部变量的场景。
内容的提问来源于stack exchange,提问作者Sten Tarvo
相关产品推荐
相关产品推荐

