The letter near a digit constant in C++?
What does the letter near the digit constant mean? Just for example:
int number = 0;
float decimal = 2.5f;
number = decimal;
What's difference betweet 2.5f and f2.5 ? I have already looked in manuals, but I really cant understand i开发者_运维知识库t. Explaine it me please in a simple format.
The value 2.5 would be a double, whereas 2.5f is a float. Unless you have a specific reason not to, it is generally better to use doubles rather than floats - they are more precise and may even be faster.
From here:
Floating-point constants default to type double. By using the suffixes f or l (or F or L — the suffix is not case sensitive), the constant can be specified as float or long double, respectively.
I don't thing the format f2.5 is legal.
What's difference betweet 2.5f and f2.5
- 2.5f is the value 2.5 as a floating point number,
- f2.5 is a variable called "f2" followed by ".5" which would be a syntax error.
Purely as additional information (not really a direct answer to the question) I'd note that to specify the type of a character or string literal, you use a prefix (e.g., L"wide string"), whereas with a numeric literal you use a suffix (e.g., 2L or 3.5f).
C++0x adds quite a few more of both prefixes and suffixes to specify more data types (e.g., there are currently only narrow and wide string literals, but C++0x will have narrow, wide, Unicode, raw, and probably at least a couple more I can't think of at the moment). It also adds user-defined literals that let you define your own suffixes, so something like 150km
could be used to create a distance
object, or "127.0.0.1"ip
to create an IP_address
object.
f2.5
is illegal. 2.5f
(or 2.5F
) forces 2.5 to be interpreted as a float, not as double. Relatedly, there's the l
/L
suffix to make integer constants long
s.
number = decimal
truncates the latter, I suppose.
精彩评论