Home > Software design >  value always coming back as 0 when the answer should not be 0
value always coming back as 0 when the answer should not be 0

Time:05-15

Trying to get a value back that usually should return 20 to 30 as s with this code

int s = sentences / wordcount * 100;

both sentences and wordcount come out as the values they should neither of which are 0. The result of them would be small (0.20 to 0.30) so thinking it might be to do with that?

CodePudding user response:

Try casting the division to a floating point (FP) value explicitly, this should prevent the result of

sentences / wordcount

from being floored to zero. You should only need to cast one to be a FP value. Try

int s = (double) sentences / wordcount * 100

CodePudding user response:

My guess is that sentences and wordcount are ints. As result you have integer divisions that is rounded to an integer before multiplying by 100. Note that integer division is not commutative.

A simple fix is move multiplication by 100 before division by wordcount.

int s = sentences * 100 / wordcount;

Though the better solution would be using float or double.

float s = (float)sentence / wordcount * 100;
  •  Tags:  
  • c
  • Related