首页 文章

从C中的函数输出多个值

提问于
浏览
0

我是编程的新手,我正在尝试构建一个执行以下操作的代码:

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中计算的值带入我的main .

在此先感谢您的帮助!如果您需要更多信息或某些内容尚不清楚,请与我们联系 .

2 回答

  • 4

    如果我正确理解您的需求,您可以使用自定义结构或内置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;
    }
    

    demo

  • 0

    您可以使用pass by reference从函数中获取多个值 . 示例代码如下:

    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
    }
    

相关问题