Average calculation problem between int and float

1

I have a problem with a mean calculation.

I have a struct with 3 fields. The ones I'm wanting to average are quantity of products and unit value. I need to average between all products and their prices. However, when I have unit values with 0.50 for example, it does not add to the calculation and only averages values that start with a minimum of 1.00. The quantity is int and the value is float.

The sum and mean 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);
    
asked by anonymous 11.05.2014 / 00:17

2 answers

1

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

media=soma/n;

type

media = soma / ((double) n);
    
19.05.2014 / 23:22
1

@ Vinícius, for you to make the correct input I would recommend using the Formatted Input feature of scanf

When you read from the keyboard, it assigns to a string that you then use strtol() to transform 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 will solve the problem.

    
20.05.2014 / 00:28