微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

计算子矩阵中所有元素总和的平均值的函数

如何解决计算子矩阵中所有元素总和的平均值的函数


我想做一个带三个参数的函数

  1. 二维数组。 (int array[rows][cols])
  2. 一个整数。 (int n)
  3. 数组地址[i][j]。

意味着我的函数原型应该看起来像这样 double Sub_avg(int arr[rows][cols],int n,int *arr[i][j])


功能说明

  • 一个参数是二维数组,表示将要处理的数据。

  • 这里的n代表n x n矩阵表示需要所有元素均值的方阵的维数。

  • 最后一个参数 int arr[i][j] 是子矩阵第一个元素的地址。


样本输入

  • 例如让我们采用 3x3 矩阵,
  • enter image description here

  • 我想计算子矩阵
  • List item


输出

  • 那么该函数将返回 8.25,即 (8 + 7 + 9 + 9)/4。

  1. 是否有用于此类计算的库函数或模板?
  2. 我主要关心的是如何在运行时传递二维数组,因为用户要输入数组的维度。

解决方法

通常在 C++ 中,您将使用 std::vectorstd::array 来存储数组并传递它们。但是,如果您真的需要使用普通的旧数组和指针,那么接下来我将提供我的任务解决方案。此外,在传递普通数组时,您可能会使用模板魔术,但我认为您想要一些非常简单的东西。

我对您的函数接口进行了最小程度的修改,使其足以用普通数组和指针解决任务。您应该将数组作为 int const * 传递,因为在 C/C++ 中,您不能在没有模板魔术的情况下传递 int arr[rows][cols],您还必须传递 rowscols 因为函数没有t 知道数组的维度,而不是将指针传递给子数组,您应该传递数组内的 sub_rowsub_col 位置。

另外我决定实现Sub_avg2()函数,它非常接近你的函数接口,但它更高级和复杂,因为它使用模板。同样由于模板,这意味着您的函数主体应仅放置在库的头文件 .h 中,主体应在编译时作为源代码可用。但额外的好处是这个函数做了额外的编译时间自动传递数组维度的工作。

您还可以注意到,我在代码中进行了额外的越界检查,并在出现错误时返回 0。

Try it online!

#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 举报,一经查实,本站将立刻删除。