代码之家  ›  专栏  ›  技术社区  ›  Raffaele Rossi

c++连分数输出错误

  •  0
  • Raffaele Rossi  · 技术社区  · 7 年前

    我编写了这段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 回复  |  直到 7 年前
        1
  •  2
  •   David    7 年前

    这个 abs 函数返回 int 这将是 0 . 您想使用 fabs std::abs ,后者对整型和浮点型都有重载。

        2
  •  1
  •   Alberto Miola user831258    7 年前

    问题是 abs() 作用我过去也有过类似的问题。查看此代码:

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

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

    1. 使用 fabs()
    2. 解决方法:

    像这样的

    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 );