2015-09-03 5 views
1

Я сделал квадратичный решатель уравнений с Javascript и HTML, но когда я нажимаю кнопку «рассчитать», он просто получает значения «a» и «c» и умножается на -1.Квадратичное уравнение в javascript не работает

Я начинаю с Javascript, поэтому я мало знаю об объекте.

Вот код:

var a, b, c, xone, xtwo; 
 

 
function getValues() { 
 
    function getValues() { 
 
    if (document.getElementById('signone').value == "+") { 
 
     a = document.getElementById('vara').value; 
 
    } else { 
 
     a = document.getElementById('vara').value * (-1); 
 
    } 
 
    if (document.getElementById('signtwo').value == "+") { 
 
     b = document.getElementById('varb').value; 
 
    } else { 
 
     b = document.getElementById('varb').value * (-1); 
 
    } 
 
    if (document.getElementById('signthree').value == "+") { 
 
     c = document.getElementById('varc').value; 
 
    } else { 
 
     c = document.getElementById('varc').value * (-1); 
 
    } 
 
    } 
 
} 
 

 
function getSolution() { 
 
    xone = ((-1 * b) + Math.sqrt((b * b) - 4 * a * c))/(2 * a); 
 
    xtwo = ((-1 * b) - Math.sqrt((b * b) - 4 * a * c))/(2 * a); 
 
} 
 

 
function showSolution() { 
 
    document.getElementById('showone').innerHTML = "x1 = " + xone; 
 
    document.getElementById('showtwo').innerHTML = "x2 = " + xtwo; 
 
}
<h1> Quadratic equation calculator </h1> 
 
<p>This calculator is going to find the two values of <i>x</i> of the equation typed.</br>In order to use it properly, you have to fill all of the boxes</br> 
 
    and click <q>ok</q> 
 
</p> 
 
</br> 
 
<form> 
 
    <select id="signone"> 
 
    <option value="+">+</option> 
 
    <option value="-">-</option> 
 
    </select> 
 
    <input id="vara" type="text" name="firstvar" placeholder="type the coeficient a" />x2 
 
    <select id="signtwo"> 
 
    <option value="+">+</option> 
 
    <option value="-">-</option> 
 
    </select> 
 
    <input id="varb" type="text" name="secondvar" placeholder="type the coeficient b " />x 
 
    <select id="signthree"> 
 
    <option value="+">+</option> 
 
    <option value="-">-</option> 
 
    </select> 
 
    <input id="varc" type="text" name="thirdvar" placeholder="type the coeficient c" />=0 
 
</form> 
 
</br> 
 
<button type="button" onclick="getValues();getSolution();showSolution();">Calculate</button> 
 
<p id="showone">X1 =</p> 
 
</br> 
 
<p id="showtwo">X2 =</p>

+1

'.value' возвращает строку, а не число. –

+0

Отлаживайте этого прикомандиста. Проверяйте каждую часть за один раз за один раз - выводьте каждый результат шага в console.log/alert it - и убедитесь, что он распечатывает то, что вы хотите. –

+1

@IfTrue нет такой функции. используйте 'parseFloat'. –

ответ

1

Когда вы получите значение из текстового ввода, это значение является строка и не число в JavaScript. Вот почему всякий раз, когда на нем делается операция, это приводит к NaN. Например, это «3» * -1, что приводит к NaN, потому что «3» не является числом. 3 - число, но «3» (как строка) - нет.

Это простое решение. Вы можете использовать parseInt(), который преобразует строковое значение в целое число. Однако, вероятно, лучше использовать parseFloat в случае ввода десятичного числа. Правильный код, например, будет выглядеть следующим образом:

a = parseFloat(document.getElementById('vara').value) * (-1) 

Вы также нарушая правила DRP во многих случаях «не повторяться», так как ваш код очень повторяющийся и может быть более легко ломается вниз цикл повторения. Всякий раз, когда у вас есть куча утверждений «если», как и у вас, его обычно можно разбить в цикле. Я дам вам вызов сделать это.

Как сказано ниже, (которое я пропустил), у вас также есть функция, которая дважды является проблемой.

+0

Строка будет автоматически преобразована в число, если вы работаете с ней с помощью '-','/'или' * '. Поэтому, хотя неплохо называть 'parseFloat' явно, это не проблема в его коде. – Barmar

+0

Это по-прежнему хорошая практика и позволяет избежать путаницы. –

+0

Согласен. Но предложения стиля принадлежат комментариям, а не ответам, если они напрямую не связаны с проблемой. – Barmar

0

Проблема в том, что getValues() ничего не делает. У вас есть дополнительное определение функции внутри функции, и вы никогда не вызываете внутреннюю функцию. Просто определите его один раз.

var a, b, c, xone, xtwo; 
 

 
function getValues() { 
 
    if (document.getElementById('signone').value == "+") { 
 
    a = document.getElementById('vara').value; 
 
    } else { 
 
    a = document.getElementById('vara').value * (-1); 
 
    } 
 
    if (document.getElementById('signtwo').value == "+") { 
 
    b = document.getElementById('varb').value; 
 
    } else { 
 
    b = document.getElementById('varb').value * (-1); 
 
    } 
 
    if (document.getElementById('signthree').value == "+") { 
 
    c = document.getElementById('varc').value; 
 
    } else { 
 
    c = document.getElementById('varc').value * (-1); 
 
    } 
 
} 
 

 
function getSolution() { 
 
    xone = ((-1 * b) + Math.sqrt((b * b) - 4 * a * c))/(2 * a); 
 
    xtwo = ((-1 * b) - Math.sqrt((b * b) - 4 * a * c))/(2 * a); 
 
} 
 

 
function showSolution() { 
 
    document.getElementById('showone').innerHTML = "x1 = " + xone; 
 
    document.getElementById('showtwo').innerHTML = "x2 = " + xtwo; 
 
}
<h1> Quadratic equation calculator </h1> 
 
<p>This calculator is going to find the two values of <i>x</i> of the equation typed.</br>In order to use it properly, you have to fill all of the boxes</br> 
 
    and click <q>ok</q> 
 
</p> 
 
</br> 
 
<form> 
 
    <select id="signone"> 
 
    <option value="+">+</option> 
 
    <option value="-">-</option> 
 
    </select> 
 
    <input id="vara" type="text" name="firstvar" placeholder="type the coeficient a" />x<sup>2</sup> 
 
    <select id="signtwo"> 
 
    <option value="+">+</option> 
 
    <option value="-">-</option> 
 
    </select> 
 
    <input id="varb" type="text" name="secondvar" placeholder="type the coeficient b " />x 
 
    <select id="signthree"> 
 
    <option value="+">+</option> 
 
    <option value="-">-</option> 
 
    </select> 
 
    <input id="varc" type="text" name="thirdvar" placeholder="type the coeficient c" />=0 
 
</form> 
 
</br> 
 
<button type="button" onclick="getValues();getSolution();showSolution();">Calculate</button> 
 
<p id="showone">X1 =</p> 
 
</br> 
 
<p id="showtwo">X2 =</p>

Смежные вопросы