简体   繁体   English

为什么会出现NaN错误?

[英]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. 当我显示我的答案时,我在所有值上始终遇到NaN错误,并且找不到混乱的地方。

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. 您没有为parseInt函数提供参数。 It works like this: parseInt("2") for example. 它的工作方式如下:例如parseInt("2") You probably want to use parseFloat instead of parseInt . 您可能要使用parseFloat而不是parseInt

Another remark: your data array is undefined. 另一句话:您的data数组未定义。

you have insert String in parseInt() 您在parseInt()中插入了String

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. 问题是您没有使用解析int解析任何内容。 Take a look here for some docs on parseInt. 在这里查看有关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. 编辑:根据@ d3l的建议,我调查了parseInt参数,根据问题,可能会在不添加基数参数的情况下parseInt函数出现某些意外行为。 Hence I added it to my solution. 因此,我将其添加到我的解决方案中。

Assuming you are parsing integers we can specify 10 as base. 假设您要解析整数,我们可以指定10为基数。

the problem was var lines = data[0].split("/n"); 问题是var lines = data[0].split("/n"); I used the wrong character. 我使用了错误的字符。 It was supposed to be var lines = data[0].split("\\n"); 应该是var lines = data[0].split("\\n");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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