Unexpected exit on my variable!

Asked

Viewed 22 times

0

# include <stdio.h>

float calcula_media_ponderada(int N_1, int N_2, int Peso_1, int Peso_2)
{
    float Media;
    Media = ((N_1 * Peso_1) + (N_2 * Peso_2)) / (Peso_1 + Peso_2);
    return Media; 
}

int main(void)
{
int Nota_1, Nota_2, Matricula, Peso_1, Peso_2;
float Media;
printf("Qual a matricula do aluno ? ");
scanf("%d", &Matricula);
printf("Qual a primeira nota do aluno ? ");
scanf("%d", &Nota_1);
printf("Qual o peso da primeira nota do aluno ? ");
scanf("%d", &Peso_1);
printf("Qual a segunda nota do aluno ? ");
scanf("%d", &Nota_2);
printf("Qual o peso da segunda nota do aluno ? ");
scanf("%d", &Peso_2);
Media = calcula_media_ponderada(Nota_1,Nota_2,Peso_1,Peso_2);
printf("A media do aluno da matricula %d e de %f",Matricula, Media);
return 0;
}

In my average variable here in the penultimate row if I give the following entries respectively 123 (matricula) 7 7 3 3. my correct output would be 5.8 but out 5.0 I cannot identify the error!

1 answer

0


You’re doing a whole division. By default, C assumes that the division between two integers will return an integer independent of the numbers after the comma.

To solve this error, the simplest way, the way your code is, is to cast to float at split time.

Would look like this

float calcula_media_ponderada(int N_1, int N_2, int Peso_1, int Peso_2)
{
    float Media;
    Media = ((N_1 * Peso_1) + (N_2 * Peso_2)) / (float) (Peso_1 + Peso_2);
    return Media; 
}

The cast changes the type of a variable momentarily, thus allowing you to continue operating with integer values for the rest of the program. However, it would be more appropriate for you to work with float notes, but that depends on the problem itself. Unless the problem specifies that the notes are only integer, try using float.

Good studies!

  • All right, thank you!

Browser other questions tagged

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