So, i'm kinda new on JavaScript and i got stuck on an exercise from Beecrowd (exercise number 1036).
Here is the exercise
Read 3 floating-point numbers. After, print the roots of bhaskara’s formula. If it's impossible to calculate the roots because a division by zero or a square root of a negative number, presents the message “Impossivel calcular”.
Input
Read 3 floating-point numbers (double) A, B and C.
Output
Print the result with 5 digits after the decimal point or the message if it is impossible to calculate.
link to the exercise: https://www.beecrowd.com.br/judge/en/problems/view/1036
And here is my code - Anyone know what is wrong with it
const input = `10.0
20.1
5.1`
// R1 = -0.29788
// R2 = -1.71212
/*
0.0 20.0 5.0
// Impossivel calcular
10.3 203.0 5.0
// R1 = -0.02466
// R2 = -19.68408
10.0 3.0 5.0
// Impossivel calcular
*/
// var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var lines = input.split('\n');
/**
* Escreva a sua solução aqui
* Code your solution here
* Escriba su solución aquí
*/
let a = parseFloat(lines.shift());
let b = parseFloat(lines.shift());
let c = parseFloat(lines.shift());
let delta = b * b - 4 * a * c;
if (delta < 0 || a === 0 || delta === 0) {
console.log("Impossivel calcular");
} else {
let r1 = (-b + Math.sqrt(delta)) / (2 * a);
let r2 = (-b - Math.sqrt(delta)) / (2 * a);
console.log('R1 = ' + r1.toFixed(5));
console.log('R2 = ' + r2.toFixed(5));
}
Your code seems to work just fine
Here is a simpler version
// var input = require('fs').readFileSync('/dev/stdin', 'utf8');
const input = `10.0 20.1 5.1
0.0 20.0 5.0
10.3 203.0 5.0
10.0 3.0 5.0`
input.split('\n').forEach(line => {
let [a, b, c] = line.split(" ").map(str => +str);
let delta = b * b - 4 * a * c;
if (delta <= 0 || a === 0) {
console.log("Impossivel calcular");
return;
}
let r1 = (-b + Math.sqrt(delta)) / (2 * a);
let r2 = (-b - Math.sqrt(delta)) / (2 * a);
console.log('R1 = ' + r1.toFixed(5));
console.log('R2 = ' + r2.toFixed(5));
});
<pre>
10.0 20.1 5.1
// R1 = -0.29788
// R2 = -1.71212
0.0 20.0 5.0
// Impossivel calcular
10.3 203.0 5.0
// R1 = -0.02466
// R2 = -19.68408
10.0 3.0 5.0
// Impossivel calcular
</pre>