'value always coming back as 0 when the answer should not be 0

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?

c


Solution 1:[1]

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

Solution 2:[2]

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;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jonathan Leffler
Solution 2 tstanisl