Why is this method returning 0?

Charlie :

This particular method of my program is designed to take in an array of the frequency of every letter of the alphabet within a string, e.g. {3, 5, 2, 1 ... until array has 26 items}

This method is then supposed to divide the amount of times the most frequent letter appears (let's say the letter E appears in the string 27 times) and divide it by the total number of characters to calculate it relative frequency within the string, e.g. 0.2 (meaning 20% of the string is this letter).

mostFrequentCharacter in a different method.

I have output (mostFrequentLetter(frequencyArray, 25)) and totalChars just to test they are calculating properly, and they are 4 and 34 respectively for my sample string. However, when I calculate the relative frequency it equals when it should equal 0.11764705882

What am I doing wrong?

 public static double relativeFrequency(int[] frequencyArray){
            int totalChars = 0;

        for (int i = 0; i < frequencyArray.length; i++){
            totalChars = totalChars + frequencyArray[i];
        }

        System.out.println (mostFrequentLetter(frequencyArray, 25));
        System.out.println(totalChars);

        return (mostFrequentLetter(frequencyArray, 25) / totalChars );
    }
Oleksi :

When you divide two integers, your result is also an integer, not a double. This is known as "integer division", if you want to look up more. That's causing numbers < 1 to turn into 0. Instead, try casting to double to force the math to stay in doubles:

return ((double) mostFrequentLetter(frequencyArray, 25) / totalChars );

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31384&siteId=1