如何将小数转换为不正确的分数JAVASCRIPT

时间:2017-06-25 06:38:09

标签: javascript

我有类似的东西

  function myFunction1() {
var aEquation = prompt("What is a? (if it is not there write 1)");
var bEquation = prompt("What is b?");
var cEquation = prompt("What is C?");
  var x10 = prompt("What is your first X coordinate?");
  var x20 = prompt("What is your second X coordinate?");
  var x30 = prompt("What is your thrid X coordinate?");
  var x40 = prompt("What is your fourth X coordinate?");
  var x50 = prompt("What is your fifth X coordinate?");
  var x60 = prompt("What is your sixth X coordinate?");
  var x70 = prompt("What is your seventh X coordinate?");
  var x80 = prompt("What is your eighth X coordinate?");
  var x90 = prompt("What is your ninth X coordinate?");
  document.getElementById("demo").innerHTML = "Your equation is:" + " " + aEquation + "x^2" + " " + "+" + " " + bEquation + "x" + " " + "+" + " " + cEquation;
  document.getElementById("Answerone").innerHTML = (eval(x10)*eval(x10)*aEquation)+(bEquation*eval(x10)*1)+(cEquation*1);
  document.getElementById("Answertwo").innerHTML = (eval(x20)*eval(x20)*aEquation)+(bEquation*eval(x20)*1)+(cEquation*1);
  document.getElementById("Answerthree").innerHTML = (eval(x30)*eval(x30)*aEquation)+(bEquation*eval(x30)*1)+(cEquation*1);
  document.getElementById("Answerfour").innerHTML = (eval(x40)*eval(x40)*aEquation)+(bEquation*eval(x40)*1)+(cEquation*1);
  document.getElementById("Answerfive").innerHTML = (eval(x50)*eval(x50)*aEquation)+(bEquation*eval(x50)*1)+(cEquation*1);
  document.getElementById("Answersix").innerHTML = (eval(x60)*eval(x60)*aEquation)+(bEquation*eval(x60)*1)+(cEquation*1);
  document.getElementById("Answerseven").innerHTML = (eval(x70)*eval(x70)*aEquation)+(bEquation*eval(x70)*1)+(cEquation*1);
  document.getElementById("Answereight").innerHTML = (eval(x80)*eval(x80)*aEquation)+(bEquation*eval(x80)*1)+(cEquation*1);
  document.getElementById("Answernine").innerHTML = (eval(x90)*eval(x90)*aEquation)+(bEquation*eval(x90)*1)+(cEquation*1); 
}

我知道我可以使用函数,但我现在就是这样做的。目前,如果我为x10,x20等输入一个像3/2的数字,答案将是正确的但是以十进制形式出现,如0.5,1.75等。有没有办法让它们全部作为不正确的分数出来?而不是0.5,1.75,我希望它分别显示1 / 2,1 / 4。谢谢!

1 个答案:

答案 0 :(得分:0)

当然,你要问的是非经常性的分数。

分别取分子和分母 - 如1.75为175和100,然后找到这两个数字的gcd

然后将数字除以gcd,并以a / b形式自行格式化新的分子和分母。

希望这有帮助!

编辑:

你可以写一个像这样的小脚本。你必须为每个号码做这个。 注意:这样做不会给回归的结果带来正确的结果。

<script>
function myFunction() {
    convert(".00033")
}

function gcd( a,  b)
{
    var r = a%b;
    while(r != 0)
    {
        a = b;
        b = r;
        r = a%b;
    }
    return b;
}

function convert( inp)
{
    var a="", b = 1, flag = 0;
    for( i = 0; i<inp.length; i++)
    {
        if(flag)
        {
            console.log("bing");
            b = b*10;
        }
        if(inp.charAt(i) != '.')
        {
            a += inp.charAt(i)
        }
        else
        {
            flag = 1
        }


    }
    a = parseInt(a);
    console.log(a);
    console.log(b);
    var x = gcd(a, b);
    console.log(a/x + "/" + b/x)
}
</script>