Precautions for comparing double data
Console. writeline (7.88 + 5.00 = 12.88 ); Result:FalseWhy? Analysis: We use "=" to compare the two double types that should be equal, and return the true value is completely uncertain. The principle of the computer's calculation of floating point numbers is to ensure that the necessary precision is correct, for example, double A = 0.9 + 0.2; then it can only ensure that the precision of the first digit after the decimal point is correct, the result of the addition calculated by the computer may be 1.100000001, or 1.100000002 or 1.1. That is to say, after the computer calculation, it is not guaranteed that all of the values below 0.1 are correct, therefore, it is not feasible to directly use = for comparison. We know that data is stored as 1 or 0 on a computer. Solution: To compare the two double numbers, check whether the absolute value of the subtraction is smaller than a certain value. This value is generally lower than the accuracy of the two numbers. Example: console. writeline (math. Abs (7.88 + 5.00-12.88) <0.001 ); |