错误:可能丢失精度

时间:2013-11-03 23:54:00

标签: double-precision

这是我的代码:

static int compoundBalance(double db, double dbTwo, double dbThree) {
if(dbThree == 0) return db;
return (1 + dbTwo)*compoundBalance(db, dbTwo, dbThree-1);
}

我得到了这两个错误。我不知道该怎么做。任何指导?谢谢。

Factorial.java:60: error: possible loss of precision
    if(dbThree == 0) return db;
                            ^
  required: int
  found:    double

Factorial.java:61: error: possible loss of precision
    return (1 + dbTwo)*compoundBalance(db, dbTwo, dbThree-1);
                      ^
  required: int
  found:    double
2 errors

1 个答案:

答案 0 :(得分:0)

您的方法签名表明您在实际返回double时返回int。您可以通过将签名更改为:

来解决此问题
static double compoundBalance(double db, double dbTwo, double dbThree) {

当你打算返回6.9时,这个错误就是阻止你返回类似6的东西。如果您确实需要此行为,则可以将返回值强制转换为int。

,而不是更改签名
static int compoundBalance(double db, double dbTwo, double dbThree) {
  if(dbThree == 0) return (int)db;
    return (int)((1 + dbTwo)*compoundBalance(db, dbTwo, dbThree-1));
  }
}