0

我有一个小问题,将长度转换为英尺和英寸。

我的代码:

 // input data
 this.data = 2500;

 //get feet
 this.feet = Math.floor(this.data / 304.8);

 //get inches
 let feetrestinmm = this.data - this.feet * 304.8;
 this.inches = Math.floor(feetrestinmm / 25.4);

 //get fraction inches
 let inchesrestinmm = feetrestinmm - this.inches * 25.4;
 this.toFraction(inchesrestinmm / 25.4);

 //back to mm
 this.mmValueOut = this.fractionToNumber(this.inchesFraction1 + '/' + this.inchesFraction2) + (this.inches * 25.4) + (this.feet * 304.8);
toFraction(x: number)
  {
    let tolerance = 1.0E-6;
    let h1 = 1;
    let h2 = 0;
    let k1 = 0;
    let k2 = 1;
    let b = x;
    do {
      let a = Math.floor(b);
      let aux = h1;
      h1 = a * h1 + h2;
      h2 = aux;
      aux = k1;
      k1 = a * k1 + k2;
      k2 = aux;
      b = 1 / (b - a);
    } while (Math.abs(x - h1 / k1) > x * tolerance);

    this.inchesFraction1 = h1;
    this.inchesFraction2 = k1;
  }

  fractionToNumber(fraction: string) {
    let numbers = fraction.split('/');
    return Number.parseFloat(numbers[0]) / Number.parseFloat(numbers[1]);
  }

所以我得到的 2500 毫米的结果是 8 英尺、2 英寸和 54/127。但是分数很奇怪。在在线转换器中,我得到27/64的分数。如果我计算回 mm,我得到的值小于输入值。

有人能告诉我我做错了什么吗?

4

1 回答 1

0

@Maryannah 是对的。要获得正确的值,您应该使用Math.round而不是Math.floor减少toFraction函数的返回值,如下所示:

function ggT(a, b) {
  var c, d;
  c = a; d = b;
  while ( c != d ) {
    if ( c < d )
      d = d - c
    else c = c - d
  }
  return(c);

所以你toFraction会是:

toFraction(x: number)
  {
    let tolerance = 1.0E-6;
    let h1 = 1;
    let h2 = 0;
    let k1 = 0;
    let k2 = 1;
    let b = x;
    do {
      let a = Math.floor(b);
      let aux = h1;
      h1 = a * h1 + h2;
      h2 = aux;
      aux = k1;
      k1 = a * k1 + k2;
      k2 = aux;
      b = 1 / (b - a);
    } while (Math.abs(x - h1 / k1) > x * tolerance);

    let reducer = ggT(h1,k1)

    this.inchesFraction1 = (h1/reducer);
    this.inchesFraction2 = (k1/reducer);
  }
于 2019-10-01T09:49:52.633 回答