# Specifying height and sex of students with a "while"

1

The exercise asks me to read 20 students and their respective heights and sex, and then show the average height and how many men and women we have.

What I did was the following:

``````int main() {
float altura, media;
char gen, mediam, mediaf;

printf("Cálculo de alunos e alunas e média de suas alturas\n");
printf("Digite a altura e o sexo do aluno\n");
scanf("%f", &altura);
media = media + altura;
scanf("%s", &gen);
if (gen = 'm') {
mediam = mediam + gen;
} else {
mediaf = mediaf + gen;
}

}

printf("A média de altura dos alunos é: \n%f", media);
printf("Temos %s alunos homens e %s alunos mulheres\n", mediam, mediaf);

return 0;
}+
``````

I was able to make the program read the total height of the students, but when I enter the share of the male and female students, the line reading the heights itself gives a segmentation fault error.

asked by anonymous 09.04.2018 / 15:15

0

There are several errors. If you want to count the number of men and women you must increase the variable, just like% as%, after all they do not stop being an accountant. The variable `contador` could be deleted, but I do not think it compensates.

The names of the variables are bad, because it is calling the average what is not a mean, it is an accumulator.

You can not use `contador` for comparison, this is the assignment operator. To buy use `=` . And test all possibilities and avoid doing something with wrong information, so I made the conditions of `==` more complete.

The average is only calculated at the end.

Wrong formatting of `if` .

How it works:

``````#include <stdio.h>

int main() {
float alturas = 0.0f;
int contador = 0, masculinos = 0, femininos = 0;
printf("Cálculo de alunos e alunas e média de suas alturas\n");
float altura;
char gen;
printf("Digite a altura e o sexo do aluno\n");
scanf("%f", &altura);
scanf("%s", &gen);
if (gen == 'm' || gen == 'M') masculinos++;
else if (gen == 'f' || gen == 'F') femininos++;
else continue;
alturas += altura;