I recently began learning JavaScript and decided to create a program to factor quadratic functions. The program itself is longer, and takes three users inputs (secondnum,firstnum,thirdnum) representing a,b,c in the standard form ax^2+bx+c. The program functions normally until this block of code.
function discriminant(secondnum,firstnum,thirdnum) {
var disc = Math.sqrt(Math.power(secondnum,2)-(4*firstnum*thirdnum));
return disc;
}
ans1 = ((-1*secondnum) + disc)/(2*firstnum);
ans2 = ((-1*secondnum) - disc)/(2*firstnum);
window.alert(ans1);
window.alert(ans2);
My intention of this code is creating a function which solves for the discriminant, then uses the discriminant in the quadratic formula. I believe there is something incorrect about the discriminant function. Is this the proper way to use user input in the function? I hope this question is not too specific.
Also if it matters here is an example of how I collect user input for (secondnum)
var secondnum = prompt ("enter b");
while (isNaN(secondnum) || secondnum == "") {
var secondnum = prompt ("enter a different b");
}
Thank you in advance.
I am not 100% sure on the math, but syntactically I think you are trying to do something like this
function discriminant(secondnum,firstnum,thirdnum) {
var disc = Math.sqrt(Math.pow(secondnum,2)-(4*firstnum*thirdnum));
return disc;
}
ans1 = ((-1*secondnum) + discriminant(firstnum, secondnum, thirdnum))/(2*firstnum);
ans2 = ((-1*secondnum) - discriminant(firstnum, secondnum, thirdnum))/(2*firstnum);
window.alert(ans1);
window.alert(ans2);
which will at least get your alert boxes working provided firstnum
, secondnum
and thirdnum
are declared before this block executes