You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

整数除法转double类型问题求助:112/100计算结果未达预期1.12

Fixing Integer Division to Double Mismatch in Java

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 .0 to either 112 or 100, you tell Java to treat that value as a double, which triggers floating-point division:

    double k = 112.0 / 100;
    System.out.println(k); // Outputs 1.12
    

    Or:

    double k = 112 / 100.0;
    System.out.println(k); // Also outputs 1.12
    
  • Explicitly cast one operand to double:
    You can force an integer to be treated as a double using 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:12:32