2016-11-16 205 views
0

我剛剛開始學習JavaScrpt並試圖製作代碼來計算數學公式,但它不能按我的預期工作。這是我正在處理的代碼。當我運行代碼時,如果我在B 3中輸入2並且使用公式B^2 - 4 * A * C在C中輸入4,則它應返回-23,但返回-31。有更多有經驗的人可以看看並告訴我我的錯誤在哪裏?JavaScript計算不正確

<html> 
 
<head> 
 
</head> 
 
<body> 
 

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

 

 
    <script> 
 

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

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

 
    }()); 
 

 
    </script> 
 

 
</body> 
 
</html>

+3

'^'不是指數。 – ASDFGerte

+1

您正在尋找'Math.pow()'作爲指數:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow – David

回答

3

歡迎的StackOverflow!我猜,當你寫了這個:

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

您的意思是:

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

^符號是XOR運營商,而不是冪。沒有這個符號,只有Math.pow()

另請注意,JavaScript中的變量名通常寫成小寫。我會用a,b,c而不是A,B,C(它傳統上代表類而不是對象)。這也與數學標準(我假設這是二次封閉方程)一起玩,其中大寫字母通常表示比數字更復雜的對象,如矩陣或圖形。

+1

有一個符號指數在即將推出的ECMAScript版本中:'**'。 – Xufox

1

這應該工作,只要你想:

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