我在JavaScript中的二次公式代码有什么问题?

时间:2015-08-01 06:26:30

标签: javascript

以下是我的代码。我无法弄清楚我的代码有什么问题。有人可以帮我这个吗?

function quadratic(a, b, c) {
    //var answer1
    //var answer2
    var answer1 = (-b + Math.sqrt(b ^ 2 - 4 * a * c)) / 2 * a;
    var answer2 = (-b - Math.sqrt(b ^ 2 - 4 * a * c)) / 2 * a;
    return answer1
    return answer2
}

console.log(quadratic(1, 2, 1))

1 个答案:

答案 0 :(得分:0)

试试这个:



function quadratic(a, b, c) {
  var x1 = -b / 2 / a + Math.pow(Math.pow(b, 2) - 4 * a * c, 0.5) / 2 / a;
  var x2 = -b / 2 / a - Math.pow(Math.pow(b, 2) - 4 * a * c, 0.5) / 2 / a;
  return {
    "x1": x1,
    "x2": x2
  };
}

var result = quadratic(1, 2, 1);
console.log("x1 = " + result.x1);
console.log("x2 = " + result.x2);
$('#x1').html(result.x1);
$('#x2').html(result.x2);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Result</h3>
<hr/>x1 = <span id="x1"></span>
<br/>x2 = <span id="x2"></span>
&#13;
&#13;
&#13;