Output: Nan | Bhaskara Formula (quadratic function) in javascript

Asked

Viewed 162 times

1

I’m trying to solve a problem of Uri online Judge for bhaskara formula, but my Output always comes out "Nan" and I don’t know where I went wrong!

Input: 10.0 20.1 5.1

var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var lines = input.split('\n');

var valores = Number(lines[0].split(" "));
var a = Number(valores[0]);
var b = Number(valores[1]);
var c = Number(valores[2]);

var b2 = b*b;
var delta = b2-4*(a*c);

if(delta < 0){
    console.log('Impossivel calcular');
}

var bneg = b*(-1);
var raizdelta = Math.sqrt(delta);
var divisor = a*a;

var r1 = (bneg+raizdelta)/divisor;
var r2 = (bneg-raizdelta)/divisor;

console.log('R1 = ' + r1);
console.log('R2 = ' + r2);
  • 1

    var valores = Number(lines[0].split(" ")), if valores is a number, which would be valores[0], valores[1] and valores[2]?

  • "var values" is not a number but an array of Number

2 answers

0

When adding a console.log(a) you’ll see he returns NaN (which means NotAnNumber). Hence, the error happens when you try to convert user entered text into a number.

You can use the methods parseInt(str) and parseFloat(str) to obtain numeric values from a string.

I edited an excerpt of your code without modifying its complexity, see:

var valores = "10.0 20.1 5.1".split(" ");
var a = parseFloat(valores[0]);
var b = parseFloat(valores[1]);
var c = parseFloat(valores[2]);

0

As I do not have your file with the numbers, I tested with a variable, const txt = "100 200 6", Because I think your file should look like this, right? Everything worked out fine. I believe your mistake is happening, because there must be some dirt coming along with number at the moment you give the split and when it will try to turn into number it fails. Use Trim() to clean:

   var a = Number(valores[0].trim());
   var b = Number(valores[1].trim());
   var c = Number(valores[2].trim());

One more thing: Add a Return right after the "Impossible to calculate" error to stop execution right after the error.

if(delta < 0){
  console.log('Impossivel calcular');
  return;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.