因此该计划将计算旅行期间每小时的总里程数。但是,我几次旅行的每小时总里程数翻了一番而不是保持不变。有谁知道为什么会这样?
这是我的头(.h)文件
class Distance
{
public:
Distance() :
tripMiles(0.0), tripGallons(0.0),
totalMiles(0.0), totalGallons(0.0){}
void addTrip(double miles, double gallons)
{
tripMiles = miles;
tripGallons = gallons;
totalMiles += miles;
totalGallons += gallons;
}
double getTripMiles() const {return tripMiles;}
double getTripGallons() const {return tripGallons;}
double getMilesTotal() const {return totalMiles;}
double getGallonsTotal() const {return totalGallons;}
double getTripMPG() const {return tripMiles / tripGallons; }
double getTotalMPG() const {return totalMiles / totalGallons; }
private:
double tripMiles, tripGallons;
double totalMiles, totalGallons;
};
这是我的主要文件。
#include <iostream>
#include "Distance.h"
using namespace std;
int main()
{
Distance myDistance;
double miles= 0.0;
double gallons = 0.0;
cout << "Enter miles driven (-1 to quit): ";
cin >> miles;
myDistance.addTrip(miles,gallons);
while(miles != -1)
{
cout << "\nEnter Gallons used: ";
cin >> gallons;
myDistance.addTrip(miles,gallons);
cout << "\nMPG this trip: " << myDistance.getTripMPG();
cout << "\nTotal MPG is: " << myDistance.getTotalMPG();
cout << "\nEnter miles driven (-1 to quit): ";
cin >> miles;
}
}
答案 0 :(得分:0)
你在循环开始前调用myDistance.addTrip(miles,gallons);
一次,然后再循环调用。这意味着您计算第一次旅行的里程两次。你应该删除第一个。