Alexander Barakov Alexander Barakov - 1 year ago 101
Javascript Question

JavaScript not calculating correctly

I just started studying JavaScrpt and tried to make code to calculate math formula but it doesn't work as I expected. Here's the code I'm working on. When I run the code if I type 2 in A 3 in B and 4 in C by the formula B^2 - 4 * A * C it should return -23 but it returns -31. Can someone more experienced take a look and tell me where is my mistake?


<form id="reshenie" action="">
<label for="A">a</label>
<input id="A" name="A" type="number" />
<label for="B">b</label>
<input id="B" name="B" type="number" />
<label for="C">c</label>
<input id="C" name="C" type="number" />
<input type="submit" value="submit" />
<input type="reset" value="reset" />
<label for="result">result</label>
<input id="result" name="result" type="number" />


(function () {
function presmqtane(A,B,C) {
A = parseFloat(A);
B = parseFloat(B);
C = parseFloat(C);
return (B^2 - 4 * A * C);

var reshenie = document.getElementById("reshenie");
if (reshenie) {
reshenie.onsubmit = function () {
this.result.value = presmqtane(this.A.value, this.B.value, this.C.value);
return false;




Answer Source

Welcome to StackOverflow! I'm guessing that when you wrote this:

return (B^2 - 4 * A * C);

You meant this:

return (Math.pow(B, 2) - 4 * A * C);

The ^ symbol is the XOR operator, not the exponentiation. There is no symbol for that, only Math.pow().

Also note that variable names, in Javascript, are usually written un lower-case. I would use a, b, c instead of A, B, C (which traditionally represent classes, not objects). This also plays along with the mathematical standard (I'm assuming that's the quadratic closed equation), where upper-case letters usually represent objects more complex than numbers, such as matrices or graphs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download