整数除法转double类型问题求助:112/100计算结果未达预期1.12
Hey there! Let's figure out why your code is returning 1.0 instead of the expected 1.12, and get it sorted out quickly.
The Root Cause
In Java, when you divide two integers (like 112 and 100 here), the language performs integer division by default. That means it discards any fractional part of the result, keeping only the whole number. So 112 / 100 first evaluates to 1 (since the .12 gets chopped off), and then this integer 1 is converted to a double, resulting in 1.0.
Simple Fixes
You just need to make sure Java uses floating-point division instead of integer division. Here are a few easy ways to do that:
Make one of the operands a floating-point number:
By adding.0to either112or100, you tell Java to treat that value as adouble, which triggers floating-point division:double k = 112.0 / 100; System.out.println(k); // Outputs 1.12Or:
double k = 112 / 100.0; System.out.println(k); // Also outputs 1.12Explicitly cast one operand to
double:
You can force an integer to be treated as adoubleusing a cast. Just make sure you cast one of the operands before the division happens (casting the entire expression won't work, since that would happen after integer division):double k = (double)112 / 100; System.out.println(k); // Outputs 1.12
What to Avoid
Don't cast the entire division result like this—it won't fix the issue:
double k = (double)(112 / 100); // Still gives 1.0, because 112/100 is already 1
With any of the correct fixes above, your code will output the expected 1.12!
内容的提问来源于stack exchange,提问作者Raman Sharma

