c ++继续分数输出错误

时间:2017-12-14 11:32:50

标签: java c++ c++14

我编写的Java代码非常有效:

static String getFraction(double x) {
        double limit = 1.0E-6;     
        double h1 = 1, h2 = 0, k1 = 0, k2 = 1;
        double y = x;

        do {

            double a = Math.floor(y);
            double aux = h1;
            h1 = a*h1+h2;
            h2 = aux;
            aux = k1;
            k1 = a*k1+k2;
            k2 = aux;
            y = 1/(y-a);

        } while (Math.abs(x-h1/k1) > x*limit );

        return ((int) h1) + "/" + ((int) k1);  
    }

它需要一个双精度数(6.45)并使用连续分数(129/20)返回其分数表示。这是C ++代码:

 void calc(double x) {

    double limit = 1.0E-6;     
    double h1 = 1, h2 = 0, k1 = 0, k2 = 1;
    double y = x;

    do {

        double a = floor(y);
        double aux = h1;
        h1 = a*h1+h2;
        h2 = aux;
        aux = k1;
        k1 = a*k1+k2;
        k2 = aux;
        y = 1/(y-a);

    } while (abs(x-h1/k1) > x*limit );

    std::cout << (h1) << "/" << (k1) << std::endl;  
 }

在我看来,C ++翻译与Java版本完全相同。问题是这个输出:

Java (input 6.45) --> 129/20
C++ (input 6.45) --> 6/1

有什么想法吗?我是否必须静态转换为允许浮点运算的东西?

2 个答案:

答案 0 :(得分:2)

abs函数返回int0。您希望使用fabsstd::abs,后者对积分和浮点类型都有重载。

答案 1 :(得分:1)

问题是abs()功能。我过去遇到过类似的问题。看看这段代码:

int main() {
  std::cout << abs(-85.5) << std::endl;
}

输出为85.您有两种解决方案:

  1. 使用fabs()
  2. 做一个workaroud:
  3. 像这样的东西

    double c;
    
    do {
    
      double a = floor(y);
      double aux = h1;
      h1 = a*h1+h2;
      h2 = aux;
      aux = k1;
      k1 = a*k1+k2;
      k2 = aux;
      y = 1/(y-a);
    
      if ((x-h1/k1) >= 0)
        c = x-h1/k1; 
      else
        c = -(x-h1/k1);
    
    } while (c > x*limit );