Reputation: 81342
I think my logic is flawed....
in a loop I have:
int seconds = (int) (elapsed.TotalSeconds / ItemPos) * (Count - ItemPos);
this loop updates approximately once per second....
the problem I have is that seconds always ends up with a zero (0) value.
this is because the ItemPos
value is always higher after first loop than elapsed.TotalSeconds
.
So for example:
if 3 seconds pass
ItemCount = 20 , so 3/20 = 0.15 - rounds to zero.... 0 * anything = 0......
What am I doing wrong?
Upvotes: 5
Views: 294
Reputation: 15397
Integer division always returns an int, and when your result would be 0.something, it's truncating to 0.
Make something a real value, and you're fine. Or, multiply before dividing:
int seconds = (int) ((float)elapsed.TotalSeconds / ItemPos) * (Count - ItemPos);
(See below)
or
int seconds = (int) (elapsed.TotalSeconds * (Count - ItemPos) / ItemPos);
EDIT
Based on dtb's comments, I realize I put my typecast in the wrongplace. My first line won't work (though my second still will). What's happening is you're taking the double value from TotalSeconds and dividing it by int ItemPos
to get a double. But then you're casting it to an int, which is where you get it set to 0. As Henk Holterman said, you have to add extra parenthesis, so that the typecasting is over the entire division:
int seconds = (int) ((elapsed.TotalSeconds / ItemPos) * (Count - ItemPos));
Upvotes: 6
Reputation: 273621
Your expression is interpreted as
( (int)(elapsed.TotalSeconds / ItemPos) ) * (Count - ItemPos);
You have to delay the type-cast, all you need is an extra pair of ()
:
//int seconds = (int) (elapsed.TotalSeconds / ItemPos) * (Count - ItemPos) ;
int seconds = (int) ( (elapsed.TotalSeconds / ItemPos) * (Count - ItemPos) );
Upvotes: 8