我在计算mpgTotal时遇到问题。这应该将所有mpgTankful相加,然后将它们除以相加的数量(本质上是找到mpgTankful的平均值)。我尝试实现一个计数器,但是并没有得到我想要的结果。它应该一直计数直到用户输入-1退出为止。
样本结果将是:
Miles用户输入:
加仑用户输入:
mpgTankful:
mpgTotal :(在这种情况下,mpgTankful将除以1)
Miles用户输入:
加仑用户输入:
mpgTankful:
mpgTotal :(在这种情况下,将前一个mpgTankful与当前mpgTankful相加并除以2)
Miles用户输入:
加仑用户输入:
mpgTankful:
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>
这应该使您入门。