我尝试使用javascript解决方程但它没有返回正确的值。我哪里错了?
代码:
<html>
<body>
<p>Click the button to calculate t</p>
<button onclick="myFunction()">Calculate</button>
<br/>
<br/>Enter R1:
<input type="text" id="txt1" name="text1">Enter R2:
<input type="text" id="txt2" name="text2">Enter c1:
<input type="text" id="txt3" name="text3">
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("txt1").value;
var y = document.getElementById("txt2").value;
var z = document.getElementById("txt3").value;
var t = 0.7*(x + 2*y)*z;
document.getElementById("demo").innerHTML = t;
}
</script>
</body>
</html>
答案 0 :(得分:2)
您还可以在计算表达式之前将输入项中的值转换为整数。 类似的东西:
var x = parseInt(document.getElementById("txt1").value);
var y = parseInt(document.getElementById("txt2").value);
var z = parseInt(document.getElementById("txt3").value);
if (isNaN(x) || isNaN(y) || isNaN(z)) {
document.getElementById("demo").innerHTML = "The values inserted are not valid";
}
else {
var t = 0.7*(x + 2*y)*z;
document.getElementById("demo").innerHTML = t;
}
在示例中,我还检查了插入的值是有效数字
答案 1 :(得分:-1)
var x = document.getElementById("txt1").value;
var y = document.getElementById("txt2").value;
var z = document.getElementById("txt3").value;
var a= 2*y; `enter code here`enter code here
var b= a+x;
var t= 0.7*b*z
document.getElementById("demo").innerHTML = t;
enter code here