gpt4 book ai didi

c++ - 如何将数组传递给函数?

转载 作者:搜寻专家 更新时间:2023-10-31 01:12:32 25 4
gpt4 key购买 nike

我正在尝试将用户定义的数组(此处定义为 matrix1)传递到函数 (det) 中,目的是计算行列式。任何帮助将不胜感激,我相信有一种简单的方法可以做到这一点,但我使用指针/vector 的各种尝试都是徒劳的!

#include <iostream>
#include <math.h>
#include <vector>

using namespace std;

int c, d;

int matrix1(int nS)
{
cout << "Enter the elements of first matrix: ";
int matrix1[10][10];
for (c = 0 ; c < nS ; c++ )
for (d = 0 ; d < nS ; d++ )
cin >> matrix1[c][d];

for (c = 0 ; c < nS ; c++ )
{
for (d = 0 ; d < nS ; d++ )
cout << matrix1[c][d] << "\t";
cout << endl;
}
}

int det(int nS, int matrix)
{
int det;
int iii;
for (iii = 0; iii < nS; iii++)
{
double a;
double b;
int c;
for (c = 0; c<nS; c++)
{
// cout << (iii+c)%nS << endl;
// cout << (nS-1) - (iii+c)%nS << endl;
int z = (iii+c)%nS;
cout << c << ", " << z << endl;
a *= matrix[c][z];
b *= matrix[c][(nS-1) - (iii+c)%nS];
}

det+= a-b;
}
cout << det << endl;
}

int main()
{
cout << "Enter the number of rows and columns of matrix: ";
int nS;
cin >> nS;

matrix1(nS);

det(nS, matrix1);

return 0;
}

最佳答案

您必须在主函数中声明数组,以便其他函数也能访问它。在除 main 之外的函数内声明的数组在堆栈上具有局部作用域,一旦函数体执行,它就会被销毁。

也就是说,您有两个同名的实体,一个矩阵数组和一个函数。这不会编译器使它们的名称唯一。像这样在 main 中声明矩阵数组。

int matrix[10][10] ;

现在像这样将它传递给您的输入函数 matrix1

matrix1(matrix, nS) ;

你的矩阵函数应该是这样的。

int matrix1(int matrix[][10], int nS)
{
//code runs here
}

您也可以以类似的方式将它传递给 det 函数。最好将行号和列号设为 const,这样您以后可以在程序中轻松更改它们。

const int ROWS = 10 ;
const int COLS = 10 ;

您可以在此处的类似答案中详细了解传递列号的原因以及如何将二维数组传递给函数。

2D-array as argument to function

关于c++ - 如何将数组传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13627752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com