HTML/CSS/JS初学开发计算器时x+1/2计算结果错误求助
问题原因
- 输入值类型错误:通过
document.getElementById().value拿到的用户输入默认是字符串类型,直接做+运算会执行字符串拼接而非数值加法,导致计算结果不符合预期。 - HTML语法不规范:
- 页面展示类标签
<h1>、<p>错误放置在<head>标签内,这类内容应当放在<body>中 <input>为自闭合标签,原代码中标签闭合写法错误
修正方案
将获取到的输入值转换为数值类型即可修复计算逻辑问题,同时修正HTML语法错误即可,以下是修改后的完整代码:
JS 部分
function result() { // 用Number()把输入的字符串转成数值类型 var x = Number(document.getElementById("constant").value); var y = Number(document.getElementById("height").value); var z = Number(document.getElementById("freq").value); var c = 3 * 10 ** 8; var k = x + 1; var k2 = k / 2; document.getElementById("Calculate").value = k2; }
HTML 部分
<!DOCTYPE html> <html> <head> <!-- head里可设置页面标题等元信息 --> <title>Microstrip Calculator</title> </head> <body> <h1>Microstrip Calculator</h1> <p>Enter the following values in numeric form:</p> <form> Di-Electric Constant: <input class="text" Placeholder="Enter Value" id="constant" /> <br> Di-Electric Height: <input class="text" Placeholder="Enter Value" id="height" /> <br> Operational Frequency: <input class="text" Placeholder="Enter Value" id="freq" /> <br> <br> <input type="text" id="Calculate" /> <input type="button" value="Calculate" onclick="result()"> </form> <br/> </body> </html>
内容的提问来源于stack exchange,提问作者Najeeb Qureshi
相关产品推荐
相关产品推荐

