Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To return a double, do I have to cast to double even if types are double in c#?

Tags:

c#

casting

To return a double, do I have to cast to double even if types are double?

e.g.

double a = 32.34;
double b = 234.24;

double result = a - b + 1/12 + 3/12;

Do I have to cast (double) ?

like image 734
yogurt Avatar asked May 19 '09 19:05

yogurt


2 Answers

No, you don't. However, your expression almost certainly doesn't do what you want it to.

The expressions 1/12 and 3/12 will be performed using integer arithmetic.

You probably want:

double result = a - b + 1/12d + 3/12d;

or

double result = a - b + 1/(double) 12 + 3/(double) 12;

Both of these will force the division to be performed using floating point arithmetic.

The problem here is that if both operands of an arithmetic operator are integers, then the operation is performed using integer arithmetic, even if it's part of a bigger expression which is of type double. Here, your expression is effectively:

double result = a - b + (1 / 12) + (3 / 12);

The addition and subtraction is okay, because the types of a and b force them to be performed using floating point arithmetic - but because division "binds more tightly" than addition and subtraction (i.e. it's like using the brackets above) only the immediate operands are considered.

Does that make sense?

EDIT: As it's so popular, it makes sense to include devinb's comment here too:

double result = a - b + 1.0/12.0 + 3.0/12.0;

It's all the same thing as far as the compiler is concerned - you just need to decide which is clearer for you:

(double) 1
1.0
1d
like image 110
Jon Skeet Avatar answered Sep 22 '22 06:09

Jon Skeet


Nope, no casting is needed.

like image 22
Daniel A. White Avatar answered Sep 20 '22 06:09

Daniel A. White