Cast operation precedence in C#

余生颓废 提交于 2019-12-19 16:57:34

问题


Will the differences below matter significantly in C#?

int a, b;
double result;
result = (double)a / b;
result = a / (double)b;
result = (double)a / (double)b;

Which one do you use?


回答1:


The cast will occur before the division.

In your examples, it doesn't matter which one you do as if one operand is a double, the runtime will cast/convert the other to a double as well.

This looks like a micro-optimization - not something worth worrying about or dealing with unless measurements show it is indeed a bottleneck.




回答2:


I do this:

result = (double)a / (double)b;

It may be strictly unnecessary, but generally I want to make sure that it will not do integer division, and I don't really care to remember the specific rules for this scenario, so it's easier (if a few more keystrokes) to be explicit.




回答3:


I do (double)a / b because I imagine an int to be something indivisible like a rock or something. When cast to a double it becomes divisible, like a cake. You can divide 3.0 cakes in four parts, but you can't divide three rocks in 4.0 parts. Or something. Do make any sense?



来源:https://stackoverflow.com/questions/9925726/cast-operation-precedence-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!