Average C using vectors

Asked

Viewed 6,936 times

2

I started my journey on C two days ago. I went to try to develop a function that averaged certain numbers of a vector. The function has some problem since it was to return the value of 4,5 and is returning the value of 4.00. I wonder if someone could help me?

#include <stdio.h>

int mediaVetor(float vet[], int tam){
  float media, soma = 0;
  int i;

  for(i =0; i<tam; i++){
    soma = soma + vet[i];
  }
  media = (float) soma/tam;

  return media;
}

int main(){
  float vetor[6] = {3.0, 4.3, 5.6, 2.8, 7.9, 3.4};
  float resultado;

  resultado = mediaVetor(vetor, 6);
  printf("A media dos vetores e de %.2f\n", resultado);
}
  • 3

    The type of its function should be float and not int. float mediaVetor(float vet[], int tam){

  • Wow, I didn’t notice that. Thank you.

2 answers

2

The return type of the function must be float. The cast in media = (float) soma / tam is unnecessary as the value of the operation is already a float.

#include <stdio.h>

float mediaVetor(float vet[], int tam) {
    float media, soma = 0;
    int i;

    for(i = 0; i < tam; i++){
        soma += vet[i];
    }

    media = soma / tam;

    return media;
}

int main(){
    float vetor[6] = {3.0, 4.3, 5.6, 2.8, 7.9, 3.4};
    float resultado;

    resultado = mediaVetor(vetor, 6);
    printf("A media dos vetores e de %.2f\n", resultado);
}

2


The problem is in the mediaVetor declaration. Instead of int, uses float. As below:

#include <stdio.h>

float mediaVetor(float vet[], int tam){
  float media, soma = 0;
  int i;

  for(i =0; i<tam; i++){
    soma = soma + vet[i];
  }
  media = (float) soma/tam;

  return media;
}

int main(){
  float vetor[6] = {3.0, 4.3, 5.6, 2.8, 7.9, 3.4};
  float resultado;

  resultado = mediaVetor(vetor, 6);
  printf("A media dos vetores e de %.2f\n", resultado);
}

Browser other questions tagged

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