如何解决计算子矩阵中所有元素总和的平均值的函数
- 二维数组。 (int array[rows][cols])
- 一个整数。 (int n)
- 数组地址[i][j]。
意味着我的函数原型应该看起来像这样 double Sub_avg(int arr[rows][cols],int n,int *arr[i][j])
功能说明
样本输入
- 那么该函数将返回 8.25,即 (8 + 7 + 9 + 9)/4。
解决方法
通常在 C++ 中,您将使用 std::vector 或 std::array 来存储数组并传递它们。但是,如果您真的需要使用普通的旧数组和指针,那么接下来我将提供我的任务解决方案。此外,在传递普通数组时,您可能会使用模板魔术,但我认为您想要一些非常简单的东西。
我对您的函数接口进行了最小程度的修改,使其足以用普通数组和指针解决任务。您应该将数组作为 int const *
传递,因为在 C/C++ 中,您不能在没有模板魔术的情况下传递 int arr[rows][cols]
,您还必须传递 rows
和 cols
因为函数没有t 知道数组的维度,而不是将指针传递给子数组,您应该传递数组内的 sub_row
和 sub_col
位置。
另外我决定实现Sub_avg2()
函数,它非常接近你的函数接口,但它更高级和复杂,因为它使用模板。同样由于模板,这意味着您的函数主体应仅放置在库的头文件 .h
中,主体应在编译时作为源代码可用。但额外的好处是这个函数做了额外的编译时间自动传递数组维度的工作。
您还可以注意到,我在代码中进行了额外的越界检查,并在出现错误时返回 0。
#include <iostream>
static double Sub_avg(int const * arr,int rows,int cols,int n,int sub_row,int sub_col) {
if (!arr || rows < 0 || cols < 0 || n < 0 || sub_row < 0 || sub_col < 0 || sub_row + n > rows || sub_col + n > cols)
return 0; // Just out of bounds checking. Return error.
double sum = 0;
for (size_t i = 0; i < n; ++i)
for (size_t j = 0; j < n; ++j)
sum += arr[(sub_row + i) * cols + sub_col + j];
return sum / double(n * n);
}
template <int rows,int cols>
static double Sub_avg2(int const (&arr)[rows][cols],int const * sarr) {
int sub_row = (sarr - &arr[0][0]) / cols,sub_col = (sarr - &arr[0][0]) % cols;
if (!arr || rows < 0 || cols < 0 || n < 0 || sub_row < 0 || sub_col < 0 || sub_row + n > rows || sub_col + n > cols)
return 0; // Just out of bounds checking. Return error.
double sum = 0;
for (size_t i = 0; i < n; ++i)
for (size_t j = 0; j < n; ++j)
sum += arr[sub_row + i][sub_col + j];
return sum / double(n * n);
}
int main() {
int const rows = 3,cols = 3,n = 2,sub_row = 1,sub_col = 1;
int arr[rows][cols] = {{3,5,6},{5,8,7},9,9}};
std::cout << Sub_avg((int*)arr,rows,cols,n,sub_row,sub_col) << std::endl;
std::cout << Sub_avg2(arr,&arr[sub_row][sub_col]) << std::endl;
}
输出:
8.25
8.25
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。