c ++

时间:2018-07-25 09:35:36

标签: c++ gcc floating-point

我发现了一个简单的浮点错误,我想知道是否有解决方法。我在Haiku OS中进行编译。我在Haiku r1 Alpha 4中

#include <iostream>
#include <cmath>

float P(float PV, float r, int t){
  return(r * PV/1-pow((1+r),-t));
}

int main(void){
  float PV = 100000;
  float r = .005;
  int t = 350;

  std::cout << "A loan valued at $" << PV << " at a rate of %" << r << " with a payment period of " << t << "months would be $" << P(PV,r,t) << ", per-payment.\n";

  return 0;
}

当我运行它时,P(PV,r,t)会以499.834的形式出现,它应该是500。尽管如果我设置了r = 0.06 P是正确的,并且显示为P = 6000

也许是编译器错误。我正在使用gcc 2.95.3-haiku-121101版本。

1 个答案:

答案 0 :(得分:1)

代码:

return(r * PV/1-pow((1+r),-t));

应为:

return(r * PV/(1-pow((1+r),-t)));

,预期结果约为605.718,而不是500。