In C#, why am i getting “can't cast double to float error”?

谁都会走 提交于 2020-01-11 10:57:48

问题


I have the following line of code:

    float top = shape.Y + (shape.Height / 2.0) - 4.5;

whic is failing with the error' Can't cast double to float. Shape.Y and shape.height are both type float.

What is causing this error and what is the best was to make sure top is a float (as i need to pass it into another function tha expects a float.


回答1:


Try to wrap your numbers with f, as normally 2.0 would represent a double number. You can read more about float here.

float top = shape.Y + (shape.Height / 2.0f) - 4.5f;



回答2:


The cause is that your literals 2.0 and 4.5 are of type double.

Then in your expression

 shape.Y + (shape.Height / 2.0) - 4.5

the division seems to be between a float and a double. But there's an implicit conversion from float to double (the conversion in the other direction is not implicit), so Height is "widened" to a double. Then to add Y to this double, for the same reasons, Y too is widened to a double. Then the entire expression gets type double.

But you declare your top variable as a float, and the double expression cannot be converted to float implicitly.

Fuji gave the solution: If you write the literals as 2.0f (or just 2f) and 4.5f, then the addition, division and difference will be calculated as floats all the way, and no conversions are needed.

(Actually if you give the denominator as just 2, it will be converted from int to float implicitly, but as you can tell by now it is probably easier to see the intention if you include that f.)



来源:https://stackoverflow.com/questions/15318300/in-c-why-am-i-getting-cant-cast-double-to-float-error

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