Result 994: what is the problem? {Code. I really mean I want to understand why 9.95*100 is the result of 994. 9.96, 9.97, 9.94, 9.93 is the normal result of 994. Why?
printf ("(9.95 * 100) = %d \n", (9.95 * 100));
Don't answer the question like @ ODA or xiaochun. I really mean to understand why the result is 9.95*100, and 994, 9.96, 9.97, 9.94 is normal.
Reply content:
Result 994: what is the problem?
printf ("(9.95 * 100) = %d \n", (9.95 * 100));
Don't answer the question like @ ODA or xiaochun. I really mean to understand why the result is 9.95*100, and 994, 9.96, 9.97, 9.94 is normal.
Floating point operations have loss of precision,9.95 * 100
The calculated result is994.9999999999999
The integer is to cut off the fractional part, that is994
. If we use rounding calculation, we can get995
printf ("(9.95 * 100) = %d \n", round(9.95 * 100));
Pick up any technical book and read the floating point number calculation chapter.
For example, PHP: Float-Manual
In addition, you can study the following differences:
printf ("(9.95 * 100) = %s \n", (9.95 * 100));
Two reasons: one is(9.95 * 100)
The floating point type is mandatory. converting it to an integer will result in loss of precision, that is, the decimal part is removed. Second, a coincidence occurs, that is(9.95 * 100)
The actual value is994.9999999999999
. In fact, it is not uncommon for floating point numbers to have precision problems. For more information, see here.