Recently, there was a requirement that the original integer calculation be changed to decimal calculation, leaving one decimal. As required, the data structure is changed from int to float, and the round() method is used to preserve decimal places.

The first version of the code is as follows:

B = round(a+0.1,1) c = 0 c += round(a,1)Copy the code

Round (a,1) has been used to reserve a decimal number, but the final result is 0.30000000000000004.

In fact, c += round(a,1) is the same thing as c = c + round(a,1), so after a lot of calculations, c is changed from int to float by adding float, and we know that in computers, floating-point precision is limited, so it can’t be represented exactly. It can only be replaced by an approximation, and when the floating-point numbers replaced by these approximations are used, essentially the approximations are involved in the operation, and the result is the approximation.

So the final code should be:

B = round(a + 0.1, 1) c = 0 c = round(c + a, 1)Copy the code