Average calculation problem between int and float

Asked

Viewed 4,640 times

1

I’m having a problem with an average calculation.

I have a struct with 3 fields. The ones I’m looking for are average product quantity and unit value. I need to average all the products and their prices. However, when I have unit values with 0.50 for example, it does not sum in the calculation and averages only the values that start with at least 1.00. The quantity is int and the value is float.

The sum and the average is as follows:

int x;
double soma=0,media;
for(x=0;x<n;x++)
{
    soma+=((prod[x].PRECO)*(prod[x].QTDE));
}
media=soma/n;
printf("\n\n\nA media de valor entre todos os produtos estocados eh: %.2lf", media);
  • This gives the impression of an input error. How do you collect the information for each element of the array? Remember that a type variable int cannot have values with floating comma (type 0.5).

  • 3

    show how you initialize prod[x].PRECO

  • I already noticed the bug. I was actually doing the data input using ',' instead of '.' when breaking the float.

  • Which function could use to ensure correct input, even the user using ',' and not give problems in the program?

  • To ensure correct entry uses fgets() and strtol() (and/or strtod()) validated!!

2 answers

1

C language requires explicit conversions between float, double, int and the like. In line:

media=soma/n;

write

media = soma / ((double) n);

1

@Vinicius, for you to perform the correct input I would recommend you to use the Formatted Input Feature scanf

When you read from the keyboard, it assigns to a string that you then use strtol() to turn into double

char string[30]; //exemplo de uso
double num;
scanf("%[0-9/-,.]", &leitura); // Vai permitir apenas numeros, `-`, `,` e `.`
num = strtol(string);

I think it’ll solve the problem.

Browser other questions tagged

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