gpt4 book ai didi

c++ - 将矩阵的一部分传递给函数(二维数组)

转载 作者:行者123 更新时间:2023-11-28 01:54:57 24 4
gpt4 key购买 nike

在我的程序中,我试图添加我的二维数组的一个子部分的值,一个 9 x 9 矩阵中的 3 x 3 的小盒子。我通过行和列的百分比乘以 3(模数 3)来选择那个小盒子。 (这意味着它将采用 [0][0]、[0][3] 等单元格)我希望它们成为我框的右上角,然后再添加 2 行和列,例如,如果我们从 [0][0] 开始,我们将添加 [0-2][0-2] (3 3 盒)。我通过一个函数计算它(作为使用函数的一种实践)。问题是该程序似乎只从那个小盒子中获取第一个单元格的值,当我尝试循环那个小盒子的其余部分并添加它们的值时,它没有正确获取值(或在全部)我想知道我的参数是否错误,或者我给函数提供了错误的参数。任何帮助将不胜感激。

//------------including section-----------
#include <iostream>
#include <cstdlib>
//------------using section---------------
using std::cin;
using std::cout;
using std::endl;
//-----our constants and variables---------
const int N=3; //initializing our rows and cols as constants
int counter=0, arr[N*N][N*N];
int sumofrow=0, sumofcol=0,sumsquare=0;
//-------prototypes----------------
void READ_MATRIX(int arr[][N*N]);
bool issquare(int arr[][N*N],int row, int col);
//-------main-------------
int main()
{
//calling on the function to input our matrix
READ_MATRIX(arr);

//checking what functions returned
if(counter==0)
cout<<1;
else
cout <<0;
return EXIT_SUCCESS;
}
//-----functions--------
//----readmatrix------
void READ_MATRIX(int arr[][N*N])
{
for (int row=0; row<N*N; row++)
for (int col=0; col<N*N; col++) {
cin >> arr[row][col];
if (row%3==0&&col%3==0)
issquare(arr, row, col);
}
}
//---------issquare-------------
bool issquare(int arr[][N*N],int row, int col)
{
sumsquare=0;
for (int r=0;r<3;r++) //trying to loop on values of array
for (int c=0;c<3;c++)//trying to loop {
//r+row(because row is passed into the function at 0,3,6)
//same for col.
sumsquare+=arr[r+row][c+col]; // this is where it goes wrong
}
//checking to see if sum reached a certain value..
if (sumsquare==45)
return true;
else {
counter++;
return false;
}
}

最佳答案

您是在接受值(value)之前添加值(value)。例如,当函数 READ_MATRIX() 中的 row = 0col = 0 时,您调用 issquare()3x3 框下的所有值都被接受之前。如果您已将所有值初始化为零,则对总和有贡献的唯一值是第一个值,即 arr[0][0]

您需要为 row = 2,4,8col = 2,4,8 触发 issquare() 函数>。在函数 issquare() 中,将数组索引为 arr[row-r][col-c]

关于c++ - 将矩阵的一部分传递给函数(二维数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41552804/

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