Pregunta

I have the following values:

i->fitness = 160

sum_fitness = 826135

I do the operation:

i->roulette = (int)(((i->fitness / sum_fitness)*100000) + 0.5);

But i keep getting 0 in i->roulette.

I also tried to save i->fitness / sum_fitness in a double variable and only then applying the other operations, but also this gets a 0.

I'm thinking that's because 160/826135 is such a small number, then it rounds it down to 0.

How can i overcome this?

Thank you

edit:

Thanks everyone, i eventually did this:

double temp = (double)(i->fitness);
i->roulette = (int)(((temp / sum_fitness)*100000) + 0.5);

And it worked.

All the answers are similar so it's hard to choose one.

¿Fue útil?

Solución

You line

i->roulette = (int)(((i->fitness / sum_fitness)*100000) + 0.5);

is casting the value to int which is why any float operation is truncated try

i->roulette = (((i->fitness / sum_fitness)*100000) + 0.5);

and make sure that either 'sum_fitness' or 'i->fitness' is of of a float or double type to make the division a floating point division -- if they are not you will need to cast one of them before dividing, like this

i->roulette = (((i->fitness / (double)sum_fitness)*100000) + 0.5);

If you want to make this as a integer calculation you could also try to change the order of the division and multiplication, like

i->roulette = ( i->fitness *100000) / sum_fitness;

which would work as long as you don't get any integer overflow, which in your case would occur only if fitness risk to be above 2000000.

Otros consejos

I'm thinking that's because 160/826135 is such a small number, then it rounds it down to 0.

It is integer division, and it is truncated to the integral part. So yes, it is 0, but there is no rounding. 99/100 would also be 0.

You could fix it like by casting the numerator or the denominator to double:

i->roulette = ((i->fitness / static_cast<double>(sum_fitness))*100000) + 0.5;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top