-1

This should be a quadratic equation root finder program using JavaScript. I wrote the code but there apparently is a mistake because when I click 'Calculate' the result is "x1: NaN; x2: NaN". Can somebody please show me the mistake?

function result() {
  var a = document.getElementById('a');
  var b = document.getElementById('b');
  var c = document.getElementById('c');

  var d = Math.sqrt(b*b-4*a*c);
  var divide = (2 * a);
  var x1 = (-b + d)/divide;
  var x2 = (-b - d)/divide;

  document.write("x1: " + x1 + "<br/>");
  document.write("x2: " + x2 + "<br/>");
}
CRice
  • 29,968
  • 4
  • 57
  • 70
berry11
  • 33
  • 5
  • 1
    Your code should be posted **here**. Stackoverflow is designed to be a repository for questions and answers, so the content should be available here forever; your linked site may change (and probably will if you fix your problem). – Pointy May 09 '18 at 17:08
  • Please post code not links. Also, googling "javascript math nan" gives [this](https://stackoverflow.com/questions/23999132/javascript-calculations-return-nan-as-result) as the #1 result. – Jared Smith May 09 '18 at 17:08
  • **1:** It would be better to copy your javascript directly here, links are discouraged. **2:** Your `a`, `b`, and `c` variables are references to the HTML elements, NOT the values of the input. Use the `.value` property to get the actual input contents. EG: `a = Number(document.getElementById('a').value)` – CRice May 09 '18 at 17:10
  • Also, your code make no provision for a negative discriminant, so you'll get NaNs whenever the roots are complex. – Lee Daniel Crocker May 09 '18 at 17:12

1 Answers1

2

You are assigning the input element with

var a = document.getElementById('a');

but you need the value of the input.

var a = document.getElementById('a').value;

If you need a Number, you could use an unary plus +

var a = +document.getElementById('a').value;
//      ^
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392