4

I'm doing some self-education in C#, and although I did more complex projects than this, I can't figure out what the problem is.

    private void button4_Click(object sender, EventArgs e)
    {
        int headcount = 0;
        int input = Global.inputcount;

        for (int i = 0; i < Global.inputcount; i++)
        {
            if (Global.myTextFile[i] == "F")
            {
                headcount++;
            }
        }
        float result;
        result = headcount/input; <<< that line
        button4.Text = result.ToString();
    }

This is my code, its supposed to count how many times does F occour in the myTextFile array, and it should divide that number with the number of inputs.

I debugged it many times, and everything is fine until [that] line. Result is 0 despite the fact that (headcount = ~2201) and (input = ~4321).

I used to work with pascal, I've been using C# for like 2 months so if anyone can help me out i would be grateful.

F stands for "Fej" = "Head" in Hungarian

Mike Debela
  • 1,930
  • 3
  • 18
  • 32
simongeri98
  • 51
  • 1
  • 3

3 Answers3

6

int / int performs integer division which always disregards fractional part no matter which type you assign it.

From / Operator (C# Reference)

When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2. To obtain a quotient as a rational number or fraction, give the dividend or divisor type float or type double.

You might wanna use floating-point division instead.

result = (float)headcount / input;

or

result = headcount / (float)input;

Check 7.7.2 Division operator documentation as well.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
0

Since you are expecting a INT result and both the operands are INT type, you are getting 0 as output. You may want to convert that to float operation

headcount/(input * 1.0);
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • it seems OP wants to get the ratio between headcount and total (i.e. is is expecting to get a number between 0 and1). Alaso, note that as OP you are using integer division, losing all decimal values resulting from division – Gian Paolo Jun 12 '16 at 13:22
  • @GianPaolo, Yes right. Edited answer for that. – Rahul Jun 12 '16 at 13:23
0

You didnt cast headcount or input to a float before doing the division. It is currently doing integer division, which does not include any remainders. headcount/input is the same as 2201/4321 which will equal 0 in integer division. Cast them to floats by doing result = (float)headcount/(float)input.

Enryu
  • 1,406
  • 1
  • 14
  • 26