I am not looking for a correction, just an explanation. In the snippet below, why am I getting the output as 2.000000?
#include <stdio.h>
#include <stdlib.h>
int main() {
double static const val = 0x1P1;
printf("%d\t%f\n", val, val);
return EXIT_SUCCESS;
}
Shouldn’t this be equal to 11?
I’ve never seen P used as an operator and find nothing with a quick Google search. What’s it do?
It’s a C++17 feature that allows specifying a power of two (as decimal exponent) by which the fractional part should be multiplied.
So mPn is m*1<<n? (For integer values of n)
Yeah, you could express it like that
1P1 = 1 * 2^1 = 2
Hex digits are 0-9 and A-F. I don’t think P is a digit.
From the documentation (emphasis mine):
If the floating literal begins with the character sequence
0x
or0X
, the floating literal is a hexadecimal floating literal. Otherwise, it is a decimal floating literal.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 (decimal) integer power of 2 by 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
You can find the full documentation here: cppreference.com
So in your example
0x1P1
means 116 * 2^(110) = 2Is there any reason why the base was chosen as
2
? Why not10
or16
?