Describe the averages of each row of a matrix in C

Asked

Viewed 323 times

1

Work out an algorithm that reads a 3x3 matrix of real numbers and calculates the mean of the values of each matrix row.

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

int main()
{
    int i, j;
    float matriz[3][3], media = 0, media2 = 0, media3 = 0, somaTotal, vetor[3];

    for (i = 0; i < 3; i++)
        for (j = 0; j < 3; j++)
        {
            printf("Digite os numeros: %d linha, %d coluna:  ", i, j);
            scanf_s("%f", &matriz[i][j]);

            vetor[i] = matriz[i][j];
        }
    
    media = vetor[0] / 3;
    media2 = vetor[1] / 3;
    media3 = vetor[2] / 3;
    
    printf("As medias da primeira linha :  %.2f\n", media);
    printf("As medias da segunda linha  :  %.2f\n", media2);
    printf("As medias da terceira linha  :  %.2f\n", media3);
    

    system("pause");
}

The averages give the wrong values, I’ve tried everything else I can do, someone knows the logic for it?

1 answer

1

To calculate the mean you have to add the elements of the line and divide by the amount of elements of the line.

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

int main() {
    int i, j;
    float matriz[3][3], vetor[3];

    for (i = 0; i < 3; i++) {
        vetor[i] = 0;
        for (j = 0; j < 3; j++)
        {
            printf("Digite os numeros: %d linha, %d coluna:  ", i, j);
            scanf_s("%f", &matriz[i][j]);
            vetor[i] += matriz[i][j];
        }
        vetor[i] /= 3;
    }
    for (i=0; i<3; i++)
        printf("As medias da linha %d :  %.2f\n", i, vetor[i]);
    system("pause");
}
  • Thank you very much, I managed to understand the logic of putting the answer in a loop and pulling the vector[i], inside the printf.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.