我是C++的新手,我正在努力了解数组在函数中的行为。这是矩阵向量乘法的一种尝试。
#include <stdio.h>
#define N 4
float Gi[N][N] = {{ 0.0, 0.0, 0.0, 1.0},
{ 0.0, 2.57142857, 3.42857143, 1.28571429},
{-0.0, 3.42857143, 8.57142857, 1.71428571},
{ 1.0, 1.28571429, 1.71428571, 0.14285714}};
void mult(
float vec_I[N],
float vec_V[N]){
int acc;
for(int i = 0; i<N; i++){
acc = 0;
for(int j = 0; j<N; j++){
acc += Gi[i][j]*vec_I[j];
}
vec_V[i] = acc;
}
}
float solver(){
float out[N];
float I[N] = {0.0, 0.0, 0.0, 10.0};
float V[N] = {0.0, 0.0, 0.0, 0.0};
mult(I, V);
out[0] = V[0];
out[1] = V[1];
out[2] = V[2];
out[3] = V[3];
return out;
}
int main(){
float outPrint[4];
outPrint = solver();
printf("| %d |n", outPrint[0]);
printf("| %d |n", outPrint[1]);
printf("| %d |n", outPrint[2]);
printf("| %d |n", outPrint[3]);
return 0;
}
当我试图编译时,编译器告诉我";[Error]无法将"float*"转换为"float"作为返回";,关于求解器函数的返回(线34(。我不明白为什么。
数组不是一流的公民。因此,它们不可按价值返还。您将不得不使用这样的结构包装器:
struct matrix_t
{
float data[16];
};