简体   繁体   中英

Why am i getting NaN error?

I have a program that reads a specific text file from a coding challenge that I've recieved and it takes the numbers and puts it into an array for me to solve a quadratic equation. When I go to display my answers I keep getting the NaN error on all of my values and I cant find where I messed up.

CODE

var lines = data[0].split("/n");
var numQuads = lines[0];
for (var i = 1; i < numQuads; i++){
  var fields = lines[i].split(",");
  var a = fields[0];
  var b = fields[1];
  var c = fields[2];
}
a = parseInt();
b = parseInt();
c = parseInt();
var discr = (b * b) - (4 * (a * c));
var sqrDiscr = Math.sqrt(discr);
var x = (-b + sqrDiscr) / (2*a);
var y = (-b - sqrDiscr) / (2*a);
var outputL = "The quadratic equation with coefficients A = " + a + " B = " + b + " C= " + c + " has no real roots!";
var outputW = "The quadratic equation with coefficients A = " + a + " B = " + b + " C= " + c + " has roots x = " + x + " and x = " + y;
if (discr >= 0) {
  output += outputW + "\n";
}
else {
  output += outputL + "\n\n";
}

You did not provide an argument to the parseInt function. It works like this: parseInt("2") for example. You probably want to use parseFloat instead of parseInt .

Another remark: your data array is undefined.

you have insert String in parseInt()

a = parseInt("67");
b = parseInt("3");
c = parseInt("2");

Should probably be:

a = parseInt(a);
b = parseInt(b);
c = parseInt(c);

The problem is that you are not parsing anything with your parse int. Take a look here for some docs on parseInt. Anyway that's how it should look like in your code:

a = parseInt(a, 10);
b = parseInt(b, 10);
c = parseInt(c, 10);
d = parseInt(d, 10);

EDIT: following the suggestion of @d3l I looked into the parseInt parameters, according to this question there could be some unexpected behaviours of the parseInt function without adding the radix parameter. Hence I added it to my solution.

Assuming you are parsing integers we can specify 10 as base.

the problem was var lines = data[0].split("/n"); I used the wrong character. It was supposed to be var lines = data[0].split("\\n");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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