我已经完成了很多代码。但现在最终我无法弄清楚如何从所有循环中添加totalMPG。我真的很茫然,因为我对java的经验有限。
//initialization phase
double stop = 1;
double miles = 0;
double gallons = 0;
double avgMPG = 0;
double totalMPG = 0;
double trip = 0;
// if the user enters zero it will stop the loop
while (stop != 0)
{
System.out.print("Enter a number for miles traveled, or enter 0 to exit: ");
miles = input.nextInt();
if (miles == 0)
{
//took me a while to figure out where th break goes and {} placement
break;
}
else
{
System.out.print("Enter number of gallons used: ");
gallons = input.nextInt();
avgMPG = miles/gallons;
trip++;
// i have tried multiple different ways to get totalMPG wont work
totalMPG = mpg++ / trip++;
}
System.out.println("Your average MPG is " + avgMPG);
}
System.out.println("Your total trip MPG is " + totalMPG);
}
}
答案 0 :(得分:0)
你真的只需要存储你的totalMiles和totalGallons,试试这个:
//initialization phase
double stop = 1;
double totalMiles = 0;
double totalGallons = 0;
// if the user enters zero it will stop the loop
while (stop != 0)
{
System.out.print("Enter a number for miles traveled, or enter 0 to exit: ");
double newMiles = input.nextInt();
if (newMiles == 0)
{
//took me a while to figure out where th break goes and {} placement
break;
}
else
{
System.out.print("Enter number of gallons used: ");
double newGallons = input.nextInt();
// i have tried multiple different ways to get totalMPG wont work
totalMiles += newMiles;
totalGallons += newGallons;
System.out.println("Your average MPG is " + (newMiles/newGallons));
}
}
System.out.println("Your total trip MPG is " + (totalMiles/totalGallons));
}