Newbie question (calculations)

  • Thread starter Thread starter Ivan Demkovitch
  • Start date Start date
I

Ivan Demkovitch

Hi!

I'm working on porting some fairly complex code from VB to C#.
There is some calculations involved. Also, many numeric constants involved.

Like:

a = 1/b

I'm not sure if I need to write it like:
a = ((double)1/b) in C#?

Also, there is a lot of code where integers computed together with doubles.

Do I need to include (double) in front of each one? Is there any way to
write it shorter?

Like in VB I can 3# or CDbl(3)

What about C#?

Thanks a lot!
 
-----Original Message-----
Hi!

I'm working on porting some fairly complex code from VB to C#.
There is some calculations involved. Also, many numeric constants involved.

Like:

a = 1/b

I'm not sure if I need to write it like:
a = ((double)1/b) in C#?

If a and b are already declared to be double then you
don't need anything else. The expression 1/b will be done
as a double.

If a is a double but b is an int then you would want to
force one of the terms in the division to double otherwise
it will be an integer division. Usually something like:

a = 1.0 / b;
Also, there is a lot of code where integers computed together with doubles.

Do I need to include (double) in front of each one? Is there any way to
write it shorter?

The shortest is probably just to cast using "(double)" as
necessary, but as stated above, you don't always need a
cast if one of the terms in your expression is typed as a
double then all ints will be implicitly promoted to double
in the expression.

You can also do:

Convert.ToDouble(int n)

but that is a bit more typing than just casting.

-- TB
 
Back
Top