Mean numbers of a matrix in C

Asked

Viewed 4,468 times

0

I need to create a program that will build me a matrix and give me back the media of your numbers.

I already have the matrix built but I can’t average the values.

The code I already have:

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

int main(void){
    int matriz [3][3] ={{0}}, i, j;
    for(i=0;i<3;i++){
        for(j=0;j<3;j++){
            printf("introduza numeros para a matriz nos lugares [%d][%d] \n", i+1, j+1);
            scanf("%d", &matriz[i][j]);
        }
    }
    printf("\n\t");
    printf("estes sao os valores da matriz\n\n");
    printf("\t\t matriz ordenada");
    for(i=0; i<3; i++){
        printf("\n");
        for(j=0;j<3;j++){
            printf("%6d", matriz[i][j]);
        }
    }
printf("\n");

}
  • Thank you Tiago for editing the question

  • What this print, ordered matrix test ma you see with the problem?

  • No, no. This is to build the matrix what I wanted now was to average the values of the matrix

  • but this is not building the matrix.

  • When I run this code and enter the numbers the matrix is built

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

Show 1 more comment

1 answer

2

You have to go through the whole matrix and add up the numbers, then just divide by the number of elements, which is the formula of the average.

#include <stdio.h>

int main(void) {
    int matriz [3][3] = {{0}};
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            printf("introduza numeros para a matriz nos lugares [%d][%d] \n", i+1, j+1);
            scanf("%d", &matriz[i][j]);
        }
    }
    printf("\n\testes sao os valores da matriz\n\n");
    printf("\t\t matriz ordenada");
    int soma = 0;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
           soma += matriz[i][j];
        }
    }
    printf("\nMédia: %d", soma / 9);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thank you so much for your help!!

  • @Didimaster see on [tour] the best way to say thank you.

Browser other questions tagged

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