Weird calculation

  • Thread starter Thread starter Gas
  • Start date Start date
G

Gas

I am new to C#, I want to perfoem a calculation and I have a weird out come
from the app.

Here is the code

double percentage = 0;

percentage = ctrl1.Height / (ctrl1.Height+ ctrl2.Height)

when I try to output the percentage, it is always 0.
(ctrl1.Height and ctrl2.Height are positive value)

anyone can give me some help here?
 
Hi,

You get 0 because you need to cast the result to double (since the
percentage is double).
 
Gas said:
percentage = 1.0 * ctrl1.Height / (ctrl1.Height+ ctrl2.Height)
^^^^^ add this
anyone can give me some help here?

The compiler performs the calculation on the right side with integer
arithmetics since all variables are integers. By adding '1.0' you force
the compiler to switch to floating point arithmetics.

Christian
 
Peter said:
You get 0 because you need to cast the result to double

Haven't tried it out, so maybe I'm wrong, but wouldn't that yield the
same result? Don't you instead have to cast only _one_ factor to double
to make the compiler use floating point arithmetic? (double)(1/2)
should still be 0, but (double)1/2 is 0.5. Or am I missing something?

Christian
 
You are correct. You need to cast one factor in the expression to
(double) in order to force floating point arithmetic. If you cast the
entire expression then the result will be the same.

I would suggest this rather than multiplying by 1.0 for maintenance
reasons. It's easier to understand the intent of

percentage = (double)ctrl1.Height / (ctrl1.Height+ ctrl2.Height)

than it is to understand why someone did this
percentage = 1.0 * ctrl1.Height / (ctrl1.Height+ ctrl2.Height)
 
Bruce said:
than it is to understand why someone did this
percentage = 1.0 * ctrl1.Height / (ctrl1.Height+ ctrl2.Height)

Well, since I usually use this method I understand perfectly. :) But I
agree with you that explicit casting is much clearer and easier to
understand.

Christian
 
Back
Top