私は、誤った入力タイプを検出し、ユーザーに NaN を提示する代わりに、論理的な情報を表示する方法を考えていました。
これが私のコードです:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>
<script>
window.onload = function() {
document.getElementById('calculate').onclick = function calculateQuad()
{
var inputa = document.getElementById('variablea').value;
var inputb = document.getElementById('variableb').value;
var inputc = document.getElementById('variablec').value;
root = Math.pow(inputb,2) - 4 * inputa * inputc;
root1 = (-inputb + Math.sqrt(root))/2*inputa
root2 = (-inputb + Math.sqrt(root))/2*inputa
document.getElementById('root1').value = root1;
document.getElementById('root2').value = root2;
if(root<'0')
{
document.getElementById('root1').value = 'No real solution'
document.getElementById('root2').value = 'No real solution'
}
else {
if(root=='0')
{
document.getElementById('root1').value = root1
document.getElementById('root2').value = 'No Second Answer'
}
else {
document.getElementById('root1').value = root1
document.getElementById('root2').value = root1
}
}
};
document.getElementById('erase').onclick = function()
{
document.getElementById('form1').reset();
}
}
</script>
<style>
#container
{
text-align: center;
}
</style>
</head>
<body>
<div id="container">
<h1>Quadratic Root Finder!</h1>
<form id="form1">
a:<input id="variablea" value="" type="text">
<br/>
b:<input id="variableb" value="" type="text">
<br />
c:<input id="variablec" value="" type="text">
<br />
<input id="calculate" value="Calculate!" type="button">
<input id="erase" value="Clear" type="button">
<br />
<br />
Roots:
<br />
<input id="root1" type="text" readonly>
<br />
<input id="root2" type="text" readonly>
</form>
</div>
</body>
</html>
たとえば、b
入力フィールドに 10a と入力したa = 1
とc = 0
しますが、間違った入力を検出して、「整数のみを入力してください」などをそれらの行に沿って出力できるようにしたいと考えています。