开发者

What does the floating point "f" designator signify?

开发者 https://www.devze.com 2023-02-09 11:45 出处:网络
I wonder if someone can clarify what the \"f\" behind a floating point number is used to signify? float myFloat = 12.0f;

I wonder if someone can clarify what the "f" behind a floating point number is used to signify?

float myFloat = 12.0f;

as apposed to:

float myFloat = 12.0;

I have seen this used many times but its pretty hard to find an explanation either online or in books. I am assuming its either something carried over from another language thats supported for consistency by C or maybe its there as a directive for the compiler when it comes to evalua开发者_如何转开发te the maths.

I am just curious if there is any practical difference between the "f" and using the "." to signify a floating point number?


It means it's a single-precision float rather than a double precision double.

From the C99 standard:

An unsuffixed floating constant has type double. If suffixed by the letter f or F, it has type float.

Objective-C is based on C, maybe not C99, but this convention has been around in C for a long time.


There are sometimes performance concerns when converting from float to double, and you can avoid them by using the 'f'. Also when doing say a square root, sin,cos, etc, a wild guess would say that

float answer = sqrt(12.0f)

is about 10x slower than

float answer = sqrtf(12.0f)

It really makes a difference on the phone and iPad, if you are doing millions of these kinds of operations. Stay in float if you need speed and can deal with the lower resolution. If you are not good at math, or not using much math in your program use double everywhere, as there are more gotchas when using the lower precision 32 bit float.

0

精彩评论

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