繁体   English   中英

C ++连续分数输出错误

[英]c++ continued fractions output error

我已经编写了运行良好的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

任何想法? 我是否必须静态转换某些东西才能允许浮点运算?

abs函数返回一个将为0int 您想使用fabsstd :: abs ,后者对于整数和浮点类型都有重载。

问题是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 );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM