Show character frequency in a string

1

Again here, I'm trying to print on screen the relative frequency of the character that is most often found in a chain. In order to calculate the relative frequency, the formula is as follows:

fr = Cantidad de veces que aparece el caracter / Cantidad total de caracteres de la cadena

CODE IN QUESTION:

var resultado = cadena
                .Replace(" ","")
                .OrderBy(c => c).ToArray()
                .GroupBy(c => char.ToUpperInvariant(c))
                .OrderByDescending(g => g.Count())
                .First();


            float frecuencia = resultado.Count() / cadena.Length;



            Console.WriteLine($"CARACTER '{resultado.Key}' SE REPITE {resultado.Count()} VECES Y SU FRECUENCIA ES {frecuencia}");

By running the code this is what I get |

RESULT:

ENTRY:

  

HOLAAA

DEPARTURE:

  

CHARACTER 'A' IS REPEATED THREE TIMES AND ITS FREQUENCY IS 0

I can not get the frequency to print on the screen (I get a 0), and I would have to get 0.5 (3 occurrences / 6 characters in length).

I hope you can give me a hand, I already try using Double, Decimal and var but I can not make the calculation, I do not know if it's a calculation problem or where I'm messing up.

Greetings.

    
asked by byte96 21.11.2017 в 14:22
source

1 answer

2

The problem is that you are doing the division with 2 integers, so that the result is an integer before assigning it to your float , so that you lose the fractional part.

Be sure to convert the integers to float to avoid having this problem:

float frecuencia = (float)resultado.Count() / cadena.Length;
    
answered by 21.11.2017 / 14:30
source