Please, why must a be < 0.7, when float a = 0.7? | SoloLearn: Learn to code for FREE!


Please, why must a be < 0.7, when float a = 0.7?

7/15/2020 4:10:42 PM


10 Answers

New Answer

+22 This might help you.


MiKoLa🔥3L17.4L16.2.5k=>L18.🙏IDLE , if I guess it right you mean that floating point number is smaller in fact than the declared value. The reason is precision of the representation of the number, so the number is something like 0.69998.


Both have difference too float a=0.7; Its not float value it is a double value by default float value is treat as double.if u will write like this float a=0.7f then it is float value. Double size is greater than float . here double value is assigned to( a )and a is float type so a is float but 0.7 is double so float (a)< 0.7 double hope u understood.


Thanks, Mouli and benjamin , accepted as they say😂👍


TheWh¡teCat 🇧🇬 a lay man would want to argue that 0.700001 could also be represented as 0.7, but for this binary conversions😂😂


MiKoLa🔥3L17.4L16.2.5k=>L18.🙏IDLE , it's a matter of accuracy maybe strange, but floating point numbers are represented in binary format and perfection is hard to achieve.


That's floating point binary for you. Read this: Or


MiKoLa🔥3L17.4L16.2.5k=>L18.🙏IDLE Run below code: #include <stdio.h> int main() { float a = 0.7; printf("a: %.12f\n", a); printf(" %.12f\n", 0.7); return 0; } You'll notice the difference. Floating point values have less precision than Double type values. Float have a precision up to 7 decimal places. Double have precision up to 15 decimal places. So when float value is compared with double, the float is converted to double type and thus it looses precision. That's why value of variable <a> is less than 0.7


blACk sh4d0w good explanation. I've made it into a code snippet to make it easier for op to view: A bit more info: The % indicates the start of a format specifier. The .12f means format it as decimal with 12 places. The \n is for a new line.


Floating point numbers are represented in as bits in computer memory. (0.7)base10 =(0.101100100...)base2 But there is only 8 bits for exponent part allocated to float type. So the rest of the bits may be ignored or rounded by the processor. That is why we can't do such types of comparisons. It is also a good practice not to use == and != in such cases.