开发者

Passing integers when floats are called for

If the arguments of a method call for floats to be passed, can one simply pass 10 as opposed to 10.0? I have been doing this, but often see code which specify .0 an开发者_开发百科d have been wondering if there are any reasons to do so. Thank you.


It's not necessary, but it's a good idea to use the correct type and/or add explicit casts when you do this - more for self-documentation purposes than anything else. For literal values just specify the constant as e.g. 10.0f - for variables just use a C-style typecast, e.g. (float)i.


The compiler will generally coerce numbers to the correct type, but it doesn't hurt to be explicit to promote readability.

The constant value 10.0 is actually a double to most C and C++ compilers, whereas 10.0f is a single-precision floating point number. If you're passing a variable to a function and you know the passed type is wrong, cast it using C notation (float)i or C++ notation float(i) depending on your compiler.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜