0

Write a script that reads the coefficients a, b and c of a quadratic equation ax2 + bx + c = 0 and solves it (prints its real roots). Calculates and prints its real roots. Print numbers with two digits of precision after the floating point

Here is what I've created so far :

function solve(args) {
    var a= +args[0];
    var b= +args[1];
    var c= +args[2];
    var d = b*b - (4 * a * c);
    var x1 = (-b + Math.sqrt(d)) / 2 * a;
    var x2 = (-b - Math.sqrt(d)) / 2 * a;
    if (0 > d) {
        console.log("no real roots");
    }
    else if (d > 0) {
        console.log("x1 = " + x1);
        console.log("x2 = " + x2);
    }
    else {
        x1 = -b /2*a;
        console.log("x1 =" + x1);
    }
} 

My question is how to I print the numbers with two digits of precision and is my logic wrong somewhere? The language is JavaScript. I've searched in the existing questions, but the answers don't seem to work for me.

Thank you ! I don't want to round the number. I want precision. Example x1 =3.555 output x1 =3.55

  • What does your program do now? What exactly are you getting as a result. – Sub 6 Resources Nov 01 '16 at 21:22
  • The only logic error I see is that you are computing the solution before testing whether `d` is negative. In practical terms, I'd avoid testing that `d` is exactly 0. Instead, compute the two solutions (provided `d` is not negative), convert to strings, and test whether the two roots are too close together to distinguish by comparing the strings. – Ted Hopp Nov 01 '16 at 21:22
  • Side note: please avoid text like "searched a lot" and "thank you" in the posts. If you want to demonstrate effort - make sure to provide links to solutions you've tried and why/how it did not work in your case. – Alexei Levenkov Nov 01 '16 at 21:24
  • Regarding rounding (_"I don't want to round the number"_): that's exactly what you want to do. If `x1` is 3.555, your output should be 3.56, not 3.55. If you really want to truncate to two decimal places, convert to a string, scan for the position of the decimal point (if any), and truncate the string yourself. Or use the solution shown in [this thread](http://stackoverflow.com/questions/4187146/display-two-decimal-places-no-rounding). – Ted Hopp Nov 01 '16 at 21:28
  • @sub6resources In this case :_ let a = 1.5; let b = 5; let c = 3_ The output is: _x1 = -3.0156865167015567 x2 = -6.984313483298443_ I'll try to fix my logic. –  Nov 01 '16 at 21:31
  • And @AlexeiLevenkov I will keep it in mind for the next time. I don't see why not to thank,tho. I want to show that I'm grateful when someone help me with an answer. I can't see anything bad in that. –  Nov 01 '16 at 21:32
  • Feel free to discuss that on meta.stackoverflow.com, make sure to read prior discussions on "thank you in the posts" (i.e. http://meta.stackoverflow.com/questions/288160/no-thanks-damn-it) – Alexei Levenkov Nov 01 '16 at 21:41

0 Answers0