从函数返回 C++ 中的结构

Returning Structures in C++ from functions

我正在尝试 return 来自函数的结构,但数据类型有问题。我不断从下面的代码中收到编译器错误 "No Suitable conversion function from "coefficients" to "int" exists "return coeff;""。我见过很多人遇到这些问题,因为他们在函数中定义结构,但我的是在开始时定义的。任何反馈都会很棒。

#include <iostream> //initialise the code familly used in most commands
using namespace std; //initialise the coding name space

struct coefficients {
    float A;
    float B;
    float C;
} coeff;

int matrix_multiplication(int r1,int r2,int r3,int r4,int r5) //matrix  multiplication between the readings taken and the regression matrix
{
float a1=3.2, b1=-2.8, c1=-0.8, d1=2.2, e1=-0.8; //teach the variables a1-a5   x a1 - d1 the values of the regression matrix
float a2=-3.0, b2=4.3, c2=0.9, d2=-3.4, e2=1.3;
float a3=0.9, b3=-1.6, c3=-0.1, d3=2.2, e3=-0.8;

coeff.A = (a1*r1)+(b1*r2)+(c1*r3)+(d1*r4)+(e1*r5);
coeff.B = (a2*r1)+(b2*r2)+(c2*r3)+(d2*r4)+(e2*r5);
coeff.C = (a3*r1)+(b3*r2)+(c3*r3)+(d3*r4)+(e3*r5);
return coeff;
}

改变

int matrix_multiplication(int r1,int r2,int r3,int r4,int r5)

coefficients matrix_multiplication(int r1,int r2,int r3,int r4,int r5)
//^^^^^^^^^^ <- You are returning a coefficients object, not an int.

因为 return coeff returns 一个 coefficients 对象,而不是 int

此外,尝试使用数组来简化您的代码。

您的 matrix_multiplication 函数被告知要 returning int 值,但您正在尝试 return 另一种类型。应该是这样的:

coefficients matrix_multiplication(int r1,int r2,int r3,int r4,int r5) //matrix  multiplication between the readings taken and the regression matrix