0

All I'm trying to accomplish here is to calculate the progress of my algorithm which iterates through a linked list, however when I try to divide the number of iterations by the total of elements in the linked list I alway get 0, the code is this:

double progress = iteratorCount/crawlerTechnologiesLinkedList.Count;
            Console.WriteLine("Progress:" + progress * 100);

and the debug session shows these values

debug session

I've been trying to figure out why progress equals 0.0 but to no avail. Any help will be appreciated.

oskar132
  • 794
  • 2
  • 12
  • 32
  • 2
    10 / 895 is 0.011, and the debugger doesn't have enough digits to show. Also, you are dividing integer by integer, which means the answer is 0. try to cast both to double? – Ming-Tang Apr 19 '15 at 18:41
  • 1
    http://stackoverflow.com/questions/661028/how-can-i-divide-two-integers-to-get-a-double – user Apr 19 '15 at 18:41

3 Answers3

5

You are probably just dividing an integer by an integer and because the divisor is bigger than the dividend it results in 0. Cast one of the integers to double first.

maraca
  • 8,468
  • 3
  • 23
  • 45
  • 2
    The output will look ugly then, round `progress * 100` or if you want whole nubers: `progress = count * 100 / size` – maraca Apr 19 '15 at 18:46
4

You're dividing an integer by another integer, so integer division is performed, resulting in 0. The cast to a double doesn't happen until after the integer division is already done.

To prevent this, you need to cast one (or both) of the operands to a double before dividing them.

BJ Myers
  • 6,617
  • 6
  • 34
  • 50
3
double progress = ((double) iteratorCount)/((double) crawlerTechnologiesLinkedList.Count);
Console.WriteLine("Progress:" + (progress * 100.0));

Here is what I would do to be safe.

Ming-Tang
  • 17,410
  • 8
  • 38
  • 76