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

Eclipse运行Java可读性指数计算结果不符问题求助

问题分析与解决

核心问题

你代码里的整数除法是导致计算偏差的根本原因。Java中,两个整数相除会直接舍弃小数部分,只保留整数结果,这和你手动计算时的浮点除法逻辑不一致。

拿你传入的参数举例:

  • characters=38、words=10,代码里characters/words会得到3(而非手动计算的3.8)
  • words=10、sentences=1,words/sentences结果为10(这部分是对的,但前一步的错误已经拉偏了最终结果)

代入错误逻辑计算:
471*3 + 0.5*10 -21.43 = 1413 +5 -21.43 = 1396.57,这就是你得到的错误结果。

修复方案

把除法操作中的至少一个整数转为double类型,强制触发浮点除法。修改readabilityIndex方法如下:

public static double readabilityIndex(int words, int sentences, int characters) {
    double index;
    // 将整数转为double后再执行除法,确保浮点运算
    index = 471 * ((double) characters / words) + 0.5 * ((double) words / sentences) - 21.43;
    return index;
}

或者更简洁的写法:

public static double readabilityIndex(int words, int sentences, int characters) {
    return 471 * (1.0 * characters / words) + 0.5 * (1.0 * words / sentences) - 21.43;
}

验证结果

代入参数characters=38、words=10、sentences=1:
471*(38.0/10) +0.5*(10.0/1) -21.43 = 471*3.8 +5 -21.43 = 1789.8 +5 -21.43 = 1773.37,和你手动计算的结果完全一致。

另外确认:你调用readabilityIndex时的参数顺序和方法定义的参数顺序匹配,这部分没有问题,无需调整。

内容的提问来源于stack exchange,提问作者Nightshade586

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 14:02:37