二次表达错误

问题描述

我是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语句之一为true,也将继续到下一行。我可能以为我正在返回错误消息。再次感谢。