Guard against the loss of accuracy of an integer division calculation in C ++

I came across the problem of a loss of precision, in simple terms:

There expression: l = i / 30 + j / 40 + k / 25, when seeking {i, j, k} = {50,85,27} l when the value is very simple, can immediately calculate the answer using the calculator to 4.8717, but prepared the following procedures to achieve:

int i = 50,j = 85, k = 27;

double l = i/30 + j/40 + k/25;

After the run, the results show 4.000000000!

 

     why? This is because the results in C ++ is obtained along two integers integer division are rounded off so that the values ​​are added, the result is obtained of 4.00000. Perhaps you will say, that I will not make pediatric problem, of course, the situation is such that it is easy to see, but also relatively easy to avoid, but when three members of type integer i, j, k are the class of the time, often easy to forget that they are of type integer, and write the above expression. Therefore, when writing programs, and the type of formula to unify written as:

int i = 50,j = 85, k = 27;

double l = i/30.0 + j/40.0 + k/25.0;

     This will not go wrong.

     Oh, this is a question of should have known, until now discovered, but not too late, fighting ~ O (∩_∩) O ~


Guess you like

Origin blog.csdn.net/wu694128/article/details/89402946