The 0bxxx
specifies an integer, but this can't be modified with d
or f
to convert it to a floating-point value. But you can use a cast:
float myFloat2 = (float) 0b111;
double myDouble2 = (double) 0b111;
Вопрос
why assignment of binary to float or double is causing an error.
here is my first code which works well-
float myFloat1 = 0b111; //prints 7.0
double myDouble1 = 0b111; //prints 7.0
here is the second code
float myFloat2 = 0b111f; //compiler complains ';' expected
double myDouble2 = 0b111d; //compiler complains ';' expected
In the second code compilers complains that ';' expected, what's going on in second code snippet? Any help will be greatly appreciated.
Решение
The 0bxxx
specifies an integer, but this can't be modified with d
or f
to convert it to a floating-point value. But you can use a cast:
float myFloat2 = (float) 0b111;
double myDouble2 = (double) 0b111;
Другие советы
Hi if you just use float x=7;
then it assumes 7 is integer and trying to assign to float so compile time error comes
so to make it work we have to do
float x=7f;
but if the number is starting with 0 in java it assumes it as Octal number
and for octal number you should not append anything like f or d.
so float x=0b111;
is fine instead of float x =0111f;
also remember float x=0181;
is invalid because octal number should have digits only from 0 to 7 and its having one of the digit 8.