我无法对矩阵中的列元素求和

时间:2014-12-21 14:38:17

标签: c

我需要求和,然后找到它们的平均值来计算矩阵的列或行的方差。我开始从列部分编写函数。我把总和写成for循环,但它只是给出了-431602080.00。这是我的功能:

float variance(float **varianceMatrix, int varianceRow, int varianceColumn, char
varianceSelector)   
{ 

int a, i, b;
float *varianceSum, *varianceAvg, *varianceNew;
int selectedColumn;

printf("%d rows, %d columns, %c is selected.\n", varianceRow, varianceColumn, varianceSelector);

switch(varianceSelector)
{
case 'c':

    varianceSum = (float*)malloc(varianceColumn*sizeof(float));
    varianceNew = (float*)malloc(varianceColumn*sizeof(float));
    varianceAvg = (float*)malloc(varianceColumn*sizeof(float));

    for(b = 0; b < varianceColumn; b++)
    {
        for(a = 0; a < varianceRow; a++)
            {
                varianceSum[a] += varianceMatrix[a][b]; 
            }
    }

    printf("Sum array:\n");
    for(a = 0; a < varianceColumn; a++)
    {
        printf("%f\n", varianceSum[a]);
    }

    for(a = 0; a < varianceColumn; a++)
    {
        varianceAvg[a] = varianceSum[a] / varianceRow;
    }

    for(a = 0; a < varianceColumn; a++)
    {
        printf("%d. rows average value: %d\n", a+1, varianceAvg[a]);
    }

}

}

2 个答案:

答案 0 :(得分:2)

出现问题是因为您没有初始化malloc数组的值。此外,看起来您在嵌套循环中有一个缓冲区溢出。这是固定代码:

for(b = 0; b < varianceColumn; b++)
{
    varianceSum[b] = 0;
    for(a = 0; a < varianceRow; a++)
    {
        // Using varianceSum[a] causes a buffer overrun

        // Assuming that you need to work out
        // sum of the matrix's columns
        varianceSum[b] += varianceMatrix[a][b]; 
    }
}

答案 1 :(得分:1)

varianceSum[a]未初始化。这一行:

    varianceSum[a] += varianceMatrix[a][b];

导致你的错误。

您可以使用calloc()varianceSum初始化为零。