使用C++类计算汽车移动和距离



这个程序编译但是,我需要让这个函数在x&y坐标上移动,然后输出行进的总距离。xCord 左右移动它,而 yCord 上下移动它。我想我需要更新我的int Taxicab::getDistanceTraveled(),void Taxicab::moveX(int getX),以及void Taxicab::moveX(int getX)。但是对于我的生活,不知道该怎么做才能让它正确更新。当我编译并运行时,它为我提供了 cab1 行驶距离的132617596和 cab2 上的 Y 坐标的 0。感谢您的帮助!

#ifndef TAXI_CPP
#define TAXI_CPP
class Taxicab
{
private:
int xCord;
int yCord;
int totalDist;
public:
Taxicab(); //default constructor
Taxicab(int, int); //overload constructor
int getX(); //returns X coordinate
int getY(); //returns Y coordinate
int getDistanceTraveled(); //returns distance calculation
void moveX(int); //moves X left or right
void moveY(int); //moves Y left or right 
};
#endif // !TAXI_CPP


#include "Taxi.h"
#include <iostream> 
#include <math.h>
#include <cstdlib>
using std::cout;
using std::cin;
using std::endl;
using std::abs;
Taxicab::Taxicab() //default constructor
{
}
Taxicab::Taxicab(int xCord, int yCord) //overload constructor
{
xCord = 0; //initialize to 0
yCord = 0; //initialize to 0
totalDist = 0; //initialize to 0
}
int Taxicab::getX()
{
return xCord; //return x coordinate
}
int Taxicab::getY()
{
return yCord; //return y coordinate
}
void Taxicab::moveX(int getX)
{
int moveX = 0;
moveX = moveX + getX;
}
void Taxicab::moveY(int getY)
{
int moveY = 0;
moveY = moveY + getY;
}
int Taxicab::getDistanceTraveled()
{
return abs(xCord) + abs(yCord);
}

#include <iostream>
#include "Taxi.h"
#include <math.h>
using std::cout;
using std::cin;
using std::endl;
int main()
{
Taxicab cab1;
Taxicab cab2(5, -8);
cab1.moveX(3);
cab1.moveY(-4);
cab1.moveX(-1);
cout << cab1.getDistanceTraveled() << endl;
cab2.moveY(7);
cout << cab2.getY() << endl;
}

你的构造函数没有意义。 在默认构造函数中,您必须将成员变量初始化为某些内容,否则它们的值是未定义的,可以设置为某个随机值。试试这些也许:

Taxicab::Taxicab() //default constructor
{
xCord = 0; //initialize to 0
yCord = 0; //initialize to 0
totalDist = 0; //initialize to 0
}
Taxicab::Taxicab(int xCord, int yCord) //overload constructor
{
this->xCord = xCord;
this->yCord = yCord;
totalDist = 0; //initialize to 0
}

移动出租车的方法也没有多大意义。也许这样的东西会更好:

void Taxicab::moveX(int offsetX)
{
totalDist += abs(offsetX);
xCoord += offsetX;
}
void Taxicab::moveY(int offsetY)
{
totalDist += abs(offsetY);
yCoord += offsetY;
}
int Taxicab::getDistanceTraveled()
{
return totalDist;
}

最新更新