Difference between revisions of "cpp/language/floating literal"
m (→Explanation: missed a substitution) |
|||
Line 68: | Line 68: | ||
<< .1E4f << '\n' | << .1E4f << '\n' | ||
<< 0x10.1p0 << '\n' | << 0x10.1p0 << '\n' | ||
− | << 0x1e5 << '\n'; | + | << 0x1e5 << '\n'; // integer literal, not floating point literal |
} | } | ||
|output= | |output= |
Revision as of 16:11, 16 April 2021
Floating point literal defines a compile-time constant whose value is specified in the source file.
Contents |
Syntax
digit-sequence decimal-exponent suffix(optional) | (1) | ||||||||
digit-sequence . decimal-exponent(optional) suffix(optional)
|
(2) | ||||||||
digit-sequence(optional) . digit-sequence decimal-exponent(optional) suffix(optional)
|
(3) | ||||||||
0x | 0X hex-digit-sequence hex-exponent suffix(optional)
|
(4) | (since C++17) | |||||||
0x | 0X hex-digit-sequence . hex-exponent suffix(optional)
|
(5) | (since C++17) | |||||||
0x | 0X hex-digit-sequence(optional) . hex-digit-sequence hex-exponent suffix(optional)
|
(6) | (since C++17) | |||||||
decimal-exponent has the form
e | E exponent-sign(optional) digit-sequence
|
|||||||||
hex-exponent has the form
p | P exponent-sign(optional) digit-sequence
|
(since C++17) | ||||||||
exponent-sign, if present, is either +
or -
suffix, if present, is one of f
, F
, l
, or L
. The suffix determines the type of the floating-point literal:
- (no suffix) defines double
-
f F
defines float -
l L
defines long double
Optional single quotes (' ) can be inserted between the digits as a separator, they are ignored when compiling. |
(since C++14) |
Explanation
Decimal scientific notation is used, meaning that the value of the floating-point literal is the significand multiplied by the number 10 raised to the power of decimal-exponent. E.g. the mathematical meaning of 123e4 is 123×104.
If the floating literal begins with the character sequence For a hexadecimal floating literal, the significand is interpreted as a hexadecimal rational number, and the digit-sequence of the exponent is interpreted as the integer power of 2 to which the significand has to be scaled. double d = 0x1.4p3; // hex fraction 1.4 (decimal 1.25) scaled by 2^3, that is 10.0 |
(since C++17) |
Notes
The hexadecimal floating-point literals were not part of C++ until C++17, although they can be parsed and printed by the I/O functions since C++11: both C++ I/O streams when std::hexfloat is enabled and the C I/O streams: std::printf, std::scanf, etc. See std::strtof for the format description
Example
#include <iostream> int main() { std::cout << 58. << '\n' << 4e2 << '\n' << 123.456e-67 << '\n' << .1E4f << '\n' << 0x10.1p0 << '\n' << 0x1e5 << '\n'; // integer literal, not floating point literal }
Output:
58 400 1.23456e-65 1000 16.0625 485
See also
user-defined literals(C++11) | literals with user-defined suffix |
C documentation for floating point constant
|