我在计算 mpgTotal 时遇到问题。这应该将所有 mpgTankful 加在一起,然后除以加在一起的数量(本质上是找到 mpgTankful 的平均值)。我尝试实现一个计数器,但它并没有达到我想要的效果。它应该继续计数,直到用户输入 -1 退出。
示例结果如下:
用户输入的里程:
用户输入的加仑数:
mpg满箱:
mpgTotal:(在本例中 mpgTankful 将除以 1)
用户输入的里程:
用户输入的加仑数:
mpg满箱:
mpgTotal:(在本例中将先前的 mpgTankful 与当前的 mpgTankful 相加并除以 2)
用户输入的里程:
用户输入的加仑数:
mpg满箱:
mpgTotal:(在本例中,将第一个 mpgTankful 与第二个和当前(第三个)mpgTankful 相加,然后除以 3)
var miles, //Miles driven
gallons, //Gallons used
mpgTankful, //MPG this tankful
mpgTotal, //Total MPG
mi, //Miles driven converted to integer
gal, //Gallons used converted to integer
count=0,
avg;
//Enter -1 to quit
while(miles!="-1"){
//Read in the Miles Driven from user as a String
miles=window.prompt("Enter miles (-1 to quit):");
if(miles=="-1"){
break;
}
//Read in the Gallons used from user as a String
gallons=window.prompt("Enter gallons:");
//Convert numbers from Strings to Integers
mi=parseInt(miles);
gal=parseInt(gallons);
//Calculate the MPG Tankful
mpgTankful=mi/gal;
//Calculate the Total MPG
mpgTotal+=mpgTankful;
count++;
if(count!=0){
avg=mpgTotal/count;
}
else
avg=0;
document.writeln("avg: " + avg);
//Print Results
document.writeln("<br/><br/>Miles driven: " + mi +
"<br/>Gallons used: " + gal +
"<br/>MPG this tankful: " + mpgTankful +
"<br/>Total MPG: " + mpgTotal);
}
最佳答案
你就快到了...
mpgTotal+=mpgTankful;
无法工作:第一次调用时,mpgTotal === undefined
if(count!=0)
没用..您在上面增加了一行计数...
您计算出avg
但没有输出(根据“总 MPG:”的描述):<br/>Total MPG: " + mpgTotal
在此示例中,我添加了对无效输入的循环检查(注释中的说明)。
<script>
var miles=0 //Miles driven
, gallons=0 //Gallons used
, mpgTankful=0 //MPG this tankful
, mpgTotal=0 //Total MPG
, mi=0 //Miles driven converted to integer
, gal=0 //Gallons used converted to integer
, count=0
, avg=0
; // end vars
main: while(true){ //main loop, labeled 'main'
if( (miles=prompt('Enter miles ("-1" to quit):')) === '-1' )
break main; //well.. plain english..
if( isNaN(mi=parseInt(miles, 10)) ){ //check if we get a number
alert('Please enter a number or enter "-1" to quit.');
continue main;
}
while(true){
if( (gallons=prompt('Enter gallons ("-1" to quit):')) === '-1' )
break main; //NOT this inner loop.
if( isNaN(gal=parseInt(gallons, 10)) ){ //check if we got a number
alert('Please enter a number or enter "-1" to quit.');
//no need to instruct a continue for this loop..
} else break; //this inner loop (so we can go on with 'main' below).
}
mpgTankful=mi/gal; //Calculate the MPG Tankful
mpgTotal+=mpgTankful; //Calculate the Total MPG
avg=mpgTotal/++count; //Calculate avg (and pre-increment count)
//Print Results
document.writeln( '<br/><br/>Miles driven: ' + mi
+ '<br/>Gallons used: ' + gal
+ '<br/>MPG this tankful: ' + mpgTankful
+ '<br/>Total MPG: ' + avg
);
}
document.close(); //don't forget to close the body..
</script>
这应该可以帮助您入门。
关于JavaScript 从用户输入中查找平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27008236/