[英]Outputting multiple values from a function in C++
我对编程非常陌生,并且正在尝试构建执行以下操作的代码:
1)两个返回方程的短函数。 2)在另一个函数中使用这两个方程,该方程将计算一些东西并返回两个变量。 3)然后,main将位于不同的文件中,该文件将使用步骤2中描述的函数输出的两个值。
目前,我在一个文件中有步骤1和2,而功能2是主要功能。 我从尝试做这样的事情回想起,您不能以这种方式调用多个函数。 我想我必须制作一个具有所有必要功能的头文件? 我不确定。 另外,我相信我需要创建一个结构以将值输出到函数2。
我已包含以下部分代码:
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
//Solution to the linear dispersion relationship for a horizontal bottom.
//Shallow Water Solution only
double f (double, double, double, double);
double df (double, double, double);
//Below is the struct I will then fill with the values calculated from
//linear dispersion function
struct wave_info {
double kn, L;
}
double linear_dispersion (double f, double df) {
// Deleted code...
return kn;
}
//Linear dispersion relation
double f(double kn, double omega, double g, double h) {
return f;
}
//Differential of Linear dispersion relation. Necessary for N-R method
double df(double kn, double g, double h) {
return df;
}
主要:
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main () {
/*
* Use values for wavelength (L) and wave number (k) calculated from linear
* dispersion program
*
*/
// Deleted code ...
return 0;
}
我已经删除了代码的主体,因为我对如何以这种方式调用函数感到困惑。 我的主要工具只需要使用linear_dispersion函数中计算的两个值。 我对如何使用函数f和df正确调用linear_dispersion函数感到困惑。
另外,该代码可以工作,但是我无法将linear_dispersion中计算出的值带入我的主代码中。
在此先感谢您的帮助! 让我知道您是否需要更多信息或不清楚。
如果我正确理解了您的需求,则可以使用自定义结构或内置pair
例如:
struct wave{
int k;
int L;
};
wave foo(){
//some more intelligent calculations here :)
return {5,6};
}
std::pair<int,int> foo2(){
//some more intelligent calculations here :)
return std::make_pair(4,5);
}
int main() {
wave w = foo();
std::pair<int,int> a = foo2();
cout << w.k << " " << w.L << endl;
cout << a.first << " " << a.second << endl;
return 0;
}
( 演示 )
您可以使用按引用传递来从函数中获取多个值。 下面的示例代码:
void linear_dispersion (double &f, double &df) //return type void
{
double a , b, c , d;
f = f(a,b,c,d);
df = df(a,b,c,d);
}
main()
{
double val1 , val2;
linear_dispersion (val1, val2);
cout<<val1<<","<<val2; //changed val1 & val2
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.