Share via


Why does this seemlingly sinple division always return 0?

Question

Saturday, December 20, 2008 9:06 PM

I'm racking my brains trying to figure out why this won't work.  It's in a loop that updates a progressbar:

ProgressVal = Convert.ToInt32((x / T.Nodes.Count) * 100);
progressBar1.Value = ProgressVal;

x is an int
T is a TreeNode (Count = 464)
ProgressVal is an int

Even in immediate mode, no matter how I express this with any number of type conversions or casts it always returns 0, no matter what x and the treenode count is.  If x is 10 and Count is 464:

(int)x / (int)T.Nodes.Count   // returns 0

I understand the division can produce a floating point result but I figured the Convert.ToInt32 would resolve that.

What am I missing?
Thanks!

All replies (3)

Saturday, December 20, 2008 9:19 PM âś…Answered

Hi meshman,
you are performing an integer division, which will always return 0 when x is less than T.Nodes.Count. Multilpying 0 by 100 will still produce 0...

You can either change the multiplication order or cast to a floating point data type so that the division will produce a mantissa.

Both should work:

ProgressVal = (x * 100) / T.Nodes.Count;

or

ProgressVal = (int) Math.Round ((double) x / T.Nodes.Count * 100);
 
HTH
--mc 


Saturday, December 20, 2008 9:20 PM | 1 vote

You are casting x / T.Nodes.Count * 100 to int. Since x and T.Nodes.Count are whole numbers, the result also be a whole number (ie. 0).

When using

x * 100 / T.Nodes.Count 

, the result will be correct, or you can also use 

(double)x / T.Nodes.Count * 100.0; 

Ewald


Saturday, December 20, 2008 9:25 PM

Oh, ok, whole numbers...  Got it, thanks!