EAvi
EAvi

Reputation: 1

C# Problems while calculating Letter Frequency percentage

I am very unskilled in programming and I am trying to finish this task for my class. I've looked all over the Internet but still can't find the answer.

Here I have a piece of my code which prints out letters and the number of times it was spotted in my text file:

 for (int i = 0; i < (int)char.MaxValue; i++)
    {

        if (c[i] > 0 &&
            char.IsLetter((char)i))
        {
            Console.WriteLine("Letter: {0}  Frequency: {1}",
                (char)i,
                c[i]);
        }

I've calculated the number of letters in my code using int count = s.Count(char.IsLetter); Dividing the c[i], obviously, doesn't work. I've tried several other methods but I keep getting errors. I feel like the solution is very simple but I simply can't see it. I hope that you will be willing to help me out :)

Upvotes: 0

Views: 238

Answers (2)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61952

Maybe you have an integer division when you want a floating point division? In that case, cast either the dividend or the divisor to double (the other one will be converted automatically), for example:

(double)c[i] / count

Edit: Since you write percentage, if you need to multiply by one hundred, you can also make sure that literal is a double, then if you are careful with the precedence of the operators, you can have all casts implicit. Example:

Console.WriteLine($"Letter: {(char)i}  Count: {c[i]}  Percentage {c[i] * 100.0 / count}");

The multiplication goes first because of left-associativity. The literal 100.0 has type double.

Upvotes: 0

Gavin
Gavin

Reputation: 4515

You could use a dictionary to store the frequency of each letter. You also shouldn't loop with the constraint i < (int)char.MaxValue. This will put you out of bounds unless c's length is >= char.MaxValue.

var frequency = new Dictionary<char, int>();
for (var i = 0; i < c.Length; i++)
{
    var current = (char)c[i];
    if (current > 0 && char.IsLetter(current))
    {
        if (!frequency.ContainsKey(current))
            frequency.Add(current);
        frequency[current]++;
        Console.WriteLine("Letter: {0}  Frequency: {1}", current, frequency[current]);
    }
}

Upvotes: 1

Related Questions