[英]Quadratic Expression. Bugs
我是 JavaScript 編程的初學者,這是我的第一個項目。 我正在嘗試使用標准分解方法找到二次表達式的因子。 我已經解釋了我在代碼中使用的邏輯作為主要 JavaScript 函數開頭的注釋,並且我還在代碼的末尾列出了到目前為止我檢測到的錯誤。 我完全依賴於我之前的練習的邏輯來編寫這段代碼,所以我希望從你的更正中學到很多東西。 我不知道代碼中的錯誤來自哪里。 如果您能幫我弄清楚任何問題,我將不勝感激。 謝謝你。
<!DOCTYPE html>
<html>
<head>
<title>Factorization of Quadratic Expression</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div id="box">
<div id="inner">
<p>Quadratic Equation <span id="warning">MUST</span> be in this format
<span id="format">ax<sup>2</sup> + bx + c</span></p>
<p>Use the caret symbol (<span id="caret">^</span>) for exponent, e.g x^2</p>
<input type="text" placeholder="Enter quadratic equation" id="equation" required/><br/>
<br/>
<button id="solve">Answer</button>
<p id="solution"></p>
</div>
</div>
<script type="text/javascript">
// get button and paragraph to display solution
let solution = document.getElementById('solution');
let solve = document.getElementById('solve');
// solve quadratic equation
solve.onclick = function() {
/* This is the main function of the code that finds the factors a quadratic expression.
I assume you already have an understanding of quadratic expressions but I will
explain
the logic I used in the code. Assuming you have a quadratic expression f(x),
f(x) = x^2 - 4x + 4
I first multiplied the coefficient of x^2 which is +1 in this case with the constant
which
is +4. Then I find two numbers whose product gives the value of the constant +4 and
whose
sum gives the value of the coefficient of x which is -4. The numbers are -2 and -2.
Then I substitute the numbers with the value of the coefficient of x adding the
literal.
f(x) = x^2 - 2x - 2x + 4
Next is grouping the first two quadratic coefficients and the last two using
parentheses.
f(x) = (x^2 - 2x) - (2x - 4)
The arithmetic symbol of the constant changes because once you expand it will give
you the former expression.
Next is to finding the greatest common divisors of both groups and simplify.
f(x) = x(x - 2) - 2(x - 2)
Next is getting the common factors.
f(x) = (x - 2)(x - 2) // Final answer
Last line of code outputs the answer and it is the biggest challenge I am having
because it seems I can only display a specific arithmetic symbol '+' (I chose to use
this because I wrote the code using an all positive quadritic expression) in this
case though it varies depending on the quadratic expression, like the one I used in
this comment. */
// get expression from input
let equation = document.getElementById('equation').value;
// validate expression (Only did this for fun and to get the feel of a real-world
project)
// if input was an empty string
if(equation === '') {
solution.innerHTML = 'Error: No expression found! Please fill out the input field';
}
// if a symbol is missing or is there is none
else if((equation.match(/(\+|\-)/g) === null) || (equation.match(/(\+|\-)/g).length < 2))
{
solution.innerHTML = 'Error: Missing symbol in expression';
}
// if the expression is not in the specified format
else if((equation.match(/\s/g).length < 2) || (equation.match(/\s/g).length > 2)) {
solution.innerHTML = 'Error: Missing or excess whitespace character in expression';
}
// if the exponent of x is not 2
else if(equation[equation.indexOf('^') + 1] !== 2) {
solution.innerHTML = 'Error: Exponent of x must be equal to 2';
}
// none of these validations work by the way not sure why
// get coefficient of x^2, x and the constant in the equation from input
array = equation.trim().split(''),
sign1 = array.indexOf('+'),
sign2 = array.lastIndexOf('+'),
getCoefficient_x2 = array.slice(0, array.indexOf(sign1 !== -1 ? '+' : '-') +
2).join(''),
getCoefficient_x = array.slice(array.indexOf(sign1 !== -1 ? '+' : '-') + 2,
array.lastIndexOf('+') - 1).join(''),
getConstant = array.slice(array.lastIndexOf(sign2 !== -1? '+' : '-') + 2).join(''),
cox2 = parseInt(getCoefficient_x2) || 1,
cox = parseInt(getCoefficient_x) || 1,
c = parseInt(getConstant);
// solving quadratic equation
let product = cox2 * c,
sum = cox,
factors = getFactors(product),
sum_product = [],
_gcd = 0,
gcd_ = 0,
cfactor = [];
// get factors whose product is equal to the constant and whose sum is equal to
coefficient of x
for(let i = 0; i < factors.length; i++) {
for(let j = 0; j < factors.length; j++) {
if((factors[i] * factors[j] === product) && (factors[i] + factors[j] === sum)) {
sum_product = [factors[j], factors[i]];
}
}
}
// grouping
// get greatest common divisor of both groups
_gcd = gcd(cox2, sum_product[0]);
gcd_ = gcd(sum_product[1], c);
// finding the common factors of the expression
/* since the computer never makes a mistake I will only factor the first grouping as this
will determine the other. */
cfactor.push(cox2 / _gcd, sum_product[0] / _gcd);
// expression of factorization is given as:
solution.innerHTML = `(${_gcd > 1 ? _gcd : ''}x + ${gcd_})\
(${cfactor[0] > 1 ? cfactor[0] : ''}x + ${cfactor[1]})`;
}
// function to get all negative and positive factors of a number
function getFactors(number) {
var factors = [],
i = 0;
if(number === undefined) number = 0;
for(i = -number; i <= number; i++) {
if(number % i === 0) factors.push(i);
}
return factors;
}
// function to get the greatest common divisor of two numbers
function gcd(num1, num2) {
var numFac = [], gcd, maxNum = Math.max(num1, num2);
for(let n = 1; n <= maxNum; n++) {
if(num1 % n == 0 && num2 % n == 0) {
numFac.push(n);
}
}
return Math.max(...numFac);
}
// Bugs
/* (1) Outputs an unexpected value if the coefficient of x is greater than the constant.
(2) Outputs an unexpected value if the expression uses a negative number.
(3) Outputs an unexpected value if coefficient of x and the constant have no common
factors to determine the the sum and product respectively.
(4) None of the validation codes works.
(5) I am not sure how I can vary the signs of the symbol depending on the give expression.
*/
</script>
</body>
</html>
關於第四個錯誤:您的驗證有效, solution
的內部內容正在修改,但您的最終答案正在覆蓋它。 如果您的驗證之一返回錯誤,您可以添加一個布爾變量valid = false
,並且在更改最終答案的解決方案的 innerHTML 之前,檢查是否valid = true
,如果不是,請不要打印您的最終答案。
像這樣:
var valid = true;
if (equation === '') {
solution.innerHTML = 'Error: No expression found! Please fill out the input field';
valid = false;
}
// if a symbol is missing or is there is none
else if ((equation.match(/(\+|\-)/g) === null) || (equation.match(/(\+|\-)/g).length < 2)) {
solution.innerHTML = 'Error: Missing symbol in expression';
valid = false;
}
// if the expression is not in the specified format
else if ((equation.match(/\s/g).length < 2) || (equation.match(/\s/g).length > 2)) {
solution.innerHTML = 'Error: Missing or excess whitespace character in expression';
valid = false;
}
// if the exponent of x is not 2
else if (equation[equation.indexOf('^') + 1] !== 2) {
solution.innerHTML = 'Error: Exponent of x must be equal to 2';
valid = false;
}
在你的最終答案中:
if (valid) {
solution.innerHTML = `(${_gcd > 1 ? _gcd : ''}x + ${gcd_})\
(${cfactor[0] > 1 ? cfactor[0] : ''}x + ${cfactor[1]})`;
}
非常感謝。 我明白。 我開悟了,我突然想到,即使其中一個 if 語句為真,代碼也會繼續到下一行。 我可能以為我正在返回錯誤消息。 再次感謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.