C / How to calculate the average in this program?

Asked

Viewed 896 times

2

Hello, this program asks for a number of people, then stores information in the struct. My question is: How to make the program calculate the average height? 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;
    }
  • The average is the sum by quantity, so create a variable that will receive the sum of all heights and divide it by n.

1 answer

2


To struct must be defined outside the main if you want to use for other functions.

 typedef struct {
  int n;
  int cpf;
  int idade;
  float altura; } Pessoa;
int main(){
 ...
}
  • Inside the main- Can only be accessed from within main
  • Off main - Can be accessed outside the 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 whole the result came in one piece, that is, we used this cast for the media to come in float how we want.

Type Casting

  • Average without cast: 5/3 = 2 <- Int

  • Average cast: 5/3 = 2.5 <- Float

  • 1

    I did so and it worked too ! All Right!!! float soma=0; for(i=0; i<n; i++) sum += vpn[i]. height; media=sum/n; printf("MEDIA: %.2f n",media);

  • Yeah, the problem is splitting one int on the other hand int, as you stated float soma there is no such problem already

Browser other questions tagged

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