C / How to calculate the average in this program?

2

Hello, this program asks for a number of people, then stores information in the struct. My question is: How can I calculate the average height for the program? Calculation is commenting

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

int main(){

    typedef struct {
  int cpf;
  int idade;
  float altura;

          } Pessoa;

        Pessoa *vpn;

int i, cont, n;
float media;

printf(" Insira numero de pessoas: ");
scanf("%d",&n);

vpn = (Pessoa *)malloc(n*sizeof(Pessoa));
if (vpn==NULL) return ;
//================================================
for (i=0;i<n;i++){

      printf(" Insida o CPF: " );
      scanf("%d", &(vpn[i].cpf) );

      printf(" Insida a idade: " );
      scanf("%d", &(vpn[i].idade) );

      printf(" Insida a altura: " );
      scanf("%f", &(vpn[i].altura));
      printf(" ======================\n");
    }

     media = (vpn[i].altura) / n;  //COMO SERIA ESSE CALCULO DE MÉDIA?
                                   // a média das alturas contidas em vpn altura

     printf("MEDIA: %f.\n",media); //imprima na tela a média das alturas contidas em vnp.

     return 0;
    }
    
asked by anonymous 29.08.2018 / 00:15

1 answer

2

struct must be set outside main if you want to use it for other functions.

 typedef struct {
  int n;
  int cpf;
  int idade;
  float altura; } Pessoa;
int main(){
 ...
}
  • Inside main - Can only be accessed within main
  • Out of main - Can be accessed outside main

Average = sum of heights / total number of people

int soma=0;
for(i=0; i<n; i++)
     soma += vpn[i].altura;

media=(float)soma/n;

Very important this cast (float) , as soma and vpn.altura are 2 integer the result was in integer, that is, we used this cast for the average to come in float as we want.

Type Casting

  • Untitled mean: 5/3 = 2 Int

  • Average cast: 5/3 = 2.5 Float

29.08.2018 / 00:24