我试图计算汽油里程。该功能有效,但由于某种原因,它返回一个负数,任何解决方案吗?
<!DOCTYPE HTML>
<html>
<head>
<title>Gas Mileage</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function calcMPG(en,st,gal){
var total= ((parseFloat(en) - parseFloat(st)))/(parseFloat(gal));
document.milespergal.mpg.value = total;
}
</script>
</head>
<body>
<h3>Gas Mileage</h3>
<form name="milespergal">
<p>Starting Mileage:<input type="text" value="0" name="start"><br>
Ending Mileage:<input type="text" value="0" name="end"><br>
Gallons Used:<input type="text" value="0" name="gallons"><br>
<input type="button" value="submit" onclick="calcMPG(document.milespergal.start.value,document.milespergal.end.value ,document.milespergal.gallons.value)">
<br>
Miles Per Gallon:<input value="0" type="text" name="mpg"></p>
</form>
</body>
</html>
答案 0 :(得分:1)
看起来你的参数倒退了。尝试将calcMPG
定义为:
//Reordered st & en
function calcMPG(st, en ,gal){
var total= ((parseFloat(en) - parseFloat(st)))/(parseFloat(gal));
document.milespergal.mpg.value = total;
}
这是JSFiddle