But there is a problem when we represent 0.8 in decimal 0.8 = 0.5 + 0.25 + 0.03125 + 0.01526 + ... So expressed in binary it is 0.11001100... This is infinitely long. But the computer can only represent a finite length. For example, 0.110011. When this limited binary is converted into the decimal system we are used to, it is 0.796875. That is to say, we want to save 0.8, but in fact, the computer saves 0.796875 (the computer may save The binary data is longer and is just more accurate), so the situation in your code occurs.
The solution is not to output the calculation results and just use an approximation. If you need greater precision, use higher-precision floating point numbers.
What you need to remember is that computers store floating point numbers imprecisely.
The questioner needs to understand the basic knowledge about floating point numbers. This article explains it better http://cenalulu.github.io/linux/about-denormalized-float-number/
Most floating point numbers cannot be represented accurately in computers. You can refer to the BigDecimal class in Java to represent fixed-point numbers
I ran your program, and there is no % at the end of the output. I guess that is your command line prompt.
Just like the F is:78.440002MacAir~/Temp $ in my MacAir.
The main problem is that computers use binary to represent data:
But there is a problem when we represent 0.8 in decimal
0.8 = 0.5 + 0.25 + 0.03125 + 0.01526 + ...So expressed in binary it is0.11001100...This is infinitely long. But the computer can only represent a finite length. For example,0.110011. When this limited binary is converted into the decimal system we are used to, it is0.796875. That is to say, we want to save 0.8, but in fact, the computer saves 0.796875 (the computer may save The binary data is longer and is just more accurate), so the situation in your code occurs.The solution is not to output the calculation results and just use an approximation. If you need greater precision, use higher-precision floating point numbers.
What you need to remember is that computers store floating point numbers imprecisely.
printf does not specify the decimal point length, f% displays the integer part and 6 decimal places by default
To be more precise, use lf
The questioner needs to understand the basic knowledge about floating point numbers. This article explains it better http://cenalulu.github.io/linux/about-denormalized-float-number/
Most floating point numbers cannot be represented accurately in computers. You can refer to the BigDecimal class in Java to represent fixed-point numbers
The float type has a default precision and generally cannot accurately represent a certain value
I ran your program, and there is no
%at the end of the output. I guess that is your command line prompt.Just like the
F is:78.440002MacAir~/Temp $in myMacAir.