最小的矩阵平均值

时间:2016-05-03 17:22:50

标签: c

因此我必须编写一个程序,允许输入2D矩阵并输出哪个子矩阵的平均值最小。

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int i, j, R, C, n, dim1, dim2;
    float **matrix;
    float sum, min;

    printf("Number of rows: ");         //big matrix dimensions
    scanf("%d", &R);
    printf("Number of columns: ");
    scanf("%d", &C);

    matrix = (float**)malloc(R * sizeof(float*));

    for(i = 0; i < R; i++)
        *(matrix + i) = (float*)malloc(C * sizeof(float));

    printf("Submatrix size:");
    scanf("%d", &n);

    for(i = 0; i < R; i++)
    {
        for(j = 0; j < C; j++)
        {
            scanf("%f", &matrix[i][j]);
        }
    }

    for(i = 0; i < R; i++)
    {
        for(j = 0; j < C; j++)
        {
            printf("%.2f\t", matrix[i][j]);
        }
        printf("\n");
    }

    printf("\n");


    dim1 = R - n + 1;
    dim2 = C - n + 1;
    for(int i1 = 0; i1 < dim1; i1++) {
        for(int j1 = 0; j1 < dim2; j1++) {
            sum = 0;                            // after calculating sum of a submatrix and saving it in
            // variable min, i reset it and calculate the next one
            for(i = 0; i < n; i++) {
                for(j = 0; j < n; j++) {
                    sum += matrix[i + i1][j + j1];
                    printf("%3f ", matrix[i + i1][j + j1]); //printing out submatrix elements
                    if(sum < min) min = sum;        //saving current sum to variable min if the condition is true
                }
                printf("\n");
            }
            printf("\n");
        }
    }
    printf("Minimum average of a %dx%d submatrices is %f", n, n, min / (n * n));

    return 0;
}

但是,我不知道如何计算这个特定情况下的最小值之和,输出总是0.我没有问题计算最大平均值,但我不明白为什么无论我做什么,输入总是为零。我尝试将min变量初始化为大数(我知道它有点愚蠢且不切实际),因此变量sum的值小于变量min,条件为真,但是也没有工作...

0 个答案:

没有答案