how do i use the pointer variable to change the value - c++

I am having a problem with changing the coordinate of the point to ( 7,4) using the pointer variable. I just did x = 7 and y = 4, but I don't think that is correct. Can someone help ?
What I need to do:
in main()
instantiate a Point object and initialize at the time of definition
define a pointer that points to the object defined above
using the pointer variable to
update the coordinates of the point to (7,4)
display the distance from the origin
#include <iostream>
#include <math.h>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x_coordinate, int y_coordinate);
int getVal();
double distance(double x2, double y2);
};
// Initialize the data members
Point::Point(int x_coordinate, int y_coordinate)
{
x = x_coordinate;
y = y_coordinate;
}
// Get the values of the data members.
int Point::getVal()
{
return x,y;
}
// Calculates and returns the point's distance from the origin.
double Point::distance(double x2, double y2)
{
double d;
d = sqrt( ((x2 - 0)*(x2 - 0)) + ((y2 - 0) * (y2 - 0)) );
return d;
}
//Allows user input and changes the point to (7,4) and displays the distance from origin.
int main()
{
int x,y;
cout << "Enter x coordinate followed by the y coordinate: " << endl;
cin >> x >> y;
Point p(x,y);
Point *newPointer = &p;
double theDistance = p.distance(x,y);
cout << "The point's distance from the origin is: " << theDistance << endl;
system("PAUSE");
}

To update coordinates of point, you need a new function -
void Point::UpdateCoordinates(int x0, int y0)
{
x = x0;
y = y0;
}
For distance(), I think you only need below.
double Point::distance()
{
return sqrt( x*x + y*y );
}

Related

Rotating a point around the origin in cpp?

I want to rotate a point around the origin but I keep getting errors. The mathematical part is solid but the code seems to fail when I want it to update the x and y values from the specific points. Can you guys help me?
Kind regards,
Vincent
#include <cmath>
#include <iostream>
#include <iomanip>
class Point
{
public:
double x, y;
// constructors
Point()
: x(0), y(0)
{}
Point(double X, double Y)
: x(X), y(Y)
{}
double roa(double angle)
{
double new_x = x*cos(angle) - y*sin(angle);
double new_y = x*sin(angle) + y*sin(angle);
x = new_x;
y = new_y;
return Point(x,y);
}
};
int main()
{
Point a(2,2);
a = a.roa(50);
std::cout << a << std::endl;
return 0
}
Solved! Thx for your help guys. You can find the new code below:
#include <cmath>
#include <iostream>
#include <iomanip>
class Point
{
public:
double x, y;
// constructors
Point()
: x(0), y(0)
{}
Point(double X, double Y)
: x(X), y(Y)
{}
Point roa(double angle)
{
double angle_rad = angle / (180/M_PI);
double new_x = x*cos(angle_rad) - y*sin(angle_rad);
double new_y = x*sin(angle_rad) + y*cos(angle_rad);
double x = new_x;
double y = new_y;
Point p;
p.x = new_x;
p.y = new_y;
return p;
}
};
int main()
{
Point a(2,2);
a = a.roa(360);
std::cout << a << std::endl;
return 0
}
A few issues in the code. You are returning Point(x, y) on roa() while the function returns a double which makes it unable to compile. If you want to rotate the same point, you are already setting x and y values in roa(), no need to reassign the whole variable at a = a.roa(50). Just do a.roa() with roa() modified as follows:
void roa(double angle)
{
double new_x = x*cos(angle) - y*sin(angle);
double new_y = x*sin(angle) + y*cos(angle); // mistake here as well
x = new_x;
y = new_y;
}
Finally, as bialy pointed out, the angle should be in radians not degrees!
Documentation says that angle is in radians:
http://www.cplusplus.com/reference/cmath/cos/
To convert angles to radians just
double angle_radians = angle_degrees / (180.0 / M_PI);

Calculating distance between to points of a triangle using pointers

I'm writing a program, where you input triangle point coordinates, the program checks if the triangle exists and outputs the area of the triangle. I have to use pointers in the program.
class Vertex
{
private:
int x, y;
public:
Vertex(int x, int y) : x(x), y(y) {}
int getX() {
return x;
}
int getY() {
return y;
}
float getDistance(Vertex *anotherVertex)
{
float dist;
int tempx = 0, tempy = 0;
tempx = anotherVertex->getX();
tempy = anotherVertex->getY();
dist = ((tempx - x) * (tempx - x) + (tempy - y) * (tempy - y));
return dist;
}
void setCoord(int x, int y)
{
this->x = x;
this->y = y;
}
};
class Triangle
{
private:
Vertex *a, *b, *c;
public:
Triangle()
{
a = new Vertex(0, 0);
b = new Vertex(0, 0);
c = new Vertex(0, 0);
}
void Set_coord()
{
int x1, y1, x2, y2, x3, y3;
cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;
a->setCoord(x1, y1);
b->setCoord(x2, y2);
c->setCoord(x3, y3);
}
bool existTriangle() {
float ab = a->getDistance(b);
float bc = b->getDistance(c);
float ca = c->getDistance(a);
if (ab + bc > ca && ab + ca > bc && bc + ca > ab) {
return true;
}
else {
return false;
}
}
float getArea() {
float p;
float ab = a->getDistance(b);
float bc = b->getDistance(c);
float ca = c->getDistance(a);
p = (ab + bc + ca) / 2;
return sqrt(p * ((p - ab)*(p - bc)*(p - ca)));
}
};
I'm struggling to make the getDistance function working as I'm inexperienced with using pointers, when debugging i'm getting this error in the getX() function.
Exception thrown: read access violation.
this was 0xDDDDDDDD.
EDIT:
here is my main()
int main() {
int n = 0;
cin >> n;
vector<Triangle*> vertices;
for (int i = 0; i < n; i++) {
Triangle* newVertices = new Triangle();
newVertices->Set_coord();
vertices.push_back(newVertices);
delete newVertices;
}
for (int i = 0; i < n; i++)
{
if (vertices[i]->existTriangle())
{
cout << vertices[i]->getArea();
}
}
}
The problem is in your main function ( that's why I asked you to post it:) ):
Triangle* newVertices = new Triangle();
vertices.push_back(newVertices);
delete newVertices;
You dynamically allocate memory, that is pointed to by newVertices.
You store the pointer into the vector.
You delete the memory pointed by newVertices.
As a result, now that pointer is a dangling pointer.
So, you must not delete newVertices into the loop.
Do your thing (computer areas, check it a triangle exists, etc.), and then, when you are done, start deleting your dynamically allocating memory...

Unable to change private variables using member functions

#include <iostream>
#include <string>
using namespace std;
struct Point {
private:
int xCord,yCord;
public:
void setX(int x);
void setY(int y);
int getX();
int getY();
int rotate(int x, int y, Point p1);
int moveHorizontally(int x, int a, int b);
int moveVertically(int y, int a, int b);
};
int main() {
Point p1;
p1.setX(1); //sets X
p1.setY(2); //sets Y
cout << p1.getX() << ", " << p1.getY() << endl; //prints current value of X & Y
p1.rotate(p1.getX(), p1.getY(), p1);
cout << p1.getX() << ", " << p1.getY() << endl;
return 0;
}
void Point::setX(int newX) {
xCord = newX;
}
void Point::setY(int newY) {
yCord = newY;
}
int Point::getY() { //This will just return the y Cord.
return yCord;
}
int Point::getX() { //This will just return the x Cord.
return xCord;
}
int Point::moveHorizontally(int x, int tempX, int tempY) {
//Move the point to the right if positive.
//Move the point to the left if negative.
int newX = tempX + (x);
return newX;
}
int Point::moveVertically(int y, int tempX, int tempY) {
//Move the point up if positive.
//Move the point down if negative.
int newY = tempY + (y);
return newY;
}
int Point::rotate(int tempX, int tempY, Point p1){
//(1,2) -->> (-2,1)
int tempX_DNC = tempX;
int tempY_DNC = tempY;
int quadrant;
if((tempX > 0) && (tempY > 0)) { //Quadrant 1: x(positive), y(positive) Then rotates to Quad 2
quadrant = 1;
tempX = -(tempY);
tempY = tempX_DNC;
} else if ((tempX < 0) && (tempY > 0)) { //Quadrant 2: x(negative), y(positive) Then rotates to Quad 3
quadrant = 2;
tempX = -(tempY_DNC);
tempY = tempX_DNC;
} else if ((tempX < 0) && (tempY < 0)) { //Quadrant 3: x(negative), y(negative) Then rotates to Quad 4
quadrant = 3;
tempX = -(tempY_DNC);
tempY = tempX_DNC;
} else if ((tempX > 0) && (tempY < 0)) { //Quadrant 4: x(positive), y(negative) Then rotates to Quad 1
quadrant = 4;
tempX = -(tempY_DNC);
tempY = tempX_DNC;
} else {
quadrant = 0;
}
//This will rotate the points 90* to the left.
//(1,2) will then become (-2,1)
//I could have if in quadrant1, all are positive, if in quadrant 2 the x would be negative and y would be positive
//If in quadrant 3 the x and y will both be negative, if in quadrant 4 the x would be positive and the y would be negative
cout << tempX << ", " << tempY << endl;
p1.setX(tempX);
p1.setY(tempY);
cout <<"x is: " <<p1.getX() <<endl;
cout <<"Y is: " <<p1.getY() <<endl;
}
Code is above.
So I am creating a class Point. Point has 2 private variables xCord, yCord. I want to call the rotate function and have that be able to modify the xCord, yCord but it does not. I am not sure why. I tried passing the Point p1 to the function and to see if that would fix the issue but it did not, I also tried without passing the Point p1 and just having Point p1 inside the function definition.
p1.setX(VARIABLE);
works when it is in main(). but not when I call p1.setX(VARIABLE) inside another member function.
You are passing a copy of p1 to the rotate function. Only this copy is modified.
You pass the point by value:
int rotate(int x, int y, Point p1);
^^--------pass-by-value
ie. the p1 inside the function is a copy of p1 in main that gets deleted once the function returns. If you want to change the point that is passed as parameter inside the function then pass it by reference:
int rotate(int x, int y, Point& p1);
^^--------pass-by-reference
PS: ... However, as rotate is a member function of Point you should probably rather rotate the instance on which you are calling it, change its signature to
int rotate(int x, int y);
and instead of changing the coordinates of some point passed as parameter do this:
this->setX(tempX); // this-> not really necessary, just added for clarity
this->setY(tempY);
Alternatively you keep it as is and pass the point that is supposed to be rotated as parameter, but then you should consider making the method static.
PPS: If you want to change it to pass-by-reference, you have to change the signature in the class declaration to:
int rotate(int x, int y, Point& p1);
and the definition you have to change to:
int Point::rotate(int tempX, int tempY, Point& p1) { /*...*/ }
void point::rotate() {
xcord = ycord;
ycord = xcord;
}
is all you need for basic rotation

My Gravitational Pull Algorithm behaves Oddly in Certain Situations

While trying to create my own physics engine (don't try persuading me not to), I decided to create a class for each pixel, called Particle, this system has an x and a y, and a x and y velocity, as shown below. Unfortunately, the code for calculateGravitationalVelocity doesn't abide by the laws of physics in certain situations. For example, if the x of the particle and the x of the other particle is the same, the particle will fall towards the object realistically, but when the particle gets too close, it pings off towards the positive x. I am only going to include the class source code, but I can include the source code of the other file, though it is partly written in SFML
Particle.cpp:
#include <iostream>
#include <string>
#include <math.h>
class Particle
{
private:
//Coords:
double x, y;
//Velocities:
double xVelocity = 0;
double yVelocity = 0;
//Material:
std::string material = "Generic";
//Mass:
double mass = 0;
public:
//Coords:
void setCoords(double, double);
float getCoords(char);
//Velocities:
void giveVelocity(char, float);
void setVelocity(char, float);
float getVelocity(char);
//Gravitational Velocity:
void calculateGravitationalVelocity(Particle);
//Material:
void setMaterial(std::string);
std::string getMaterial();
//Mass:
void setMass(double);
double getMass();
//Update:
void update();
};
//Coords:
void Particle::setCoords(double newX, double newY)
{
x = newX;
y = newY;
}
float Particle::getCoords(char axis)
{
if (axis == 'x')
{
//return floor(x);
return x;
}
else if (axis == 'y')
{
//return floor(y);
return y;
}
}
//Velocities:
void Particle::giveVelocity(char axis, float addedVelocity)
{
if (axis == 'x') {xVelocity = xVelocity + addedVelocity;}
else if (axis == 'y') {yVelocity = yVelocity + addedVelocity;}
}
void Particle::setVelocity(char axis, float newVelocity)
{
if (axis == 'x') {xVelocity = newVelocity;}
else if (axis == 'y') {yVelocity = newVelocity;}
}
float Particle::getVelocity(char axis)
{
if (axis == 'x') {return xVelocity;}//floor(xVelocity);}
else if (axis == 'y') {return xVelocity;}//floor(yVelocity);}
}
//Gravitational Velocity (Where the problems probably are):
void Particle::calculateGravitationalVelocity(Particle distantParticle)
{
//Physics constants:
const double pi = 3.14159265359; //Pi
const double G = 0.00000000006673; //Gravitational Constant (or Big G)
//Big Triangle Trigonometry:
//Get coords of moving particle:
double x1 = x;
double y1 = y;
//Get coords of particle with gravity:
double x2 = distantParticle.getCoords('x');
double y2 = distantParticle.getCoords('y');
if (x1 != x2)
{
//Work out the angle:
double A = atan((y2 - y1) / (x2 - x1)) * 180 / pi;
//Remove the minus sign:
A = fabs(A);
//Small Triangle Trigonometry:
//Work out the hypotenuse of the big triangle:
double hyp = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
//Work out the gravitational field (hyp of small triangle):
long double gravitationalField = G * (distantParticle.getMass() / pow(hyp, 2));
//For testing purposes:
//std::cout << "X: " << (cos(A) * gravitationalField) / 1000 << std::endl;
//std::cout << "Y: " << (sin(A) * gravitationalField) / 1000 << std::endl;
//Work out the X velocity:
xVelocity = xVelocity + (cos(A) * gravitationalField) / 1000;
//Work out the Y velocity:
yVelocity = yVelocity + (sin(A) * gravitationalField) / 1000;
}
else
{
//Work out the hypotenuse of the big triangle:
double hyp = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
//Work out the gravitational field (hyp of small triangle):
long double gravitationalField = G * (distantParticle.getMass() / pow(hyp, 2));
yVelocity = yVelocity + gravitationalField / 1000;
}
}
//Material:
void Particle::setMaterial(std::string newMaterialType)
{
material = newMaterialType;
}
std::string Particle::getMaterial()
{
return material;
}
//Mass:
void Particle::setMass(double newMass)
{
mass = newMass;
}
double Particle::getMass()
{
return mass;
}
//Update:
void Particle::update()
{
x = x + xVelocity;
y = y + yVelocity;
}
I am sorry for the very open question, and it probably goes against the rules somewhere, but I couldn't find it. The code for working out mostly uses a two triangles to make a x and y velocity. Here is an image of what I was hoping the code would do as a triangle (sorry it doesn't look great, but I like using a whiteboard):
You don't need to perform any trigonometric calculation.
...
//Get coords of particle with gravity:
double x2 = distantParticle.getCoords('x');
double y2 = distantParticle.getCoords('y');
// Get difference vector
double rx = x1 - x2;
double ry = y1 - y2;
// square of distance
double r2 = rx * rx + ry * ry;
// distance
double r = sqrt (r2);
if (r != 0) {
// normalize difference vector
double ux = rx / r;
double uy = ry / r;
// acceleration of gravity
double a = - G * distantParticle.getMass() / r2;
xVelocity += a * ux / 1000;
yVelocity += a * uy / 1000;
}
}

C++ double initialization

#include <iostream>
#include <math.h>
using namespace std;
class circle
{
public:
circle();
circle(double radius);
double circlerad(void);
double area(void);
double circumference(void);
private:
double rad;
};
circle::circle()
{
double rad = 0;
}
circle::circle(double radius)
{
cout << radius << endl;
double rad = radius;
}
double circle::circlerad(void)
{
return rad;
}
double circle::area(void)
{
double res;
res = rad * rad * 3.14;
return res;
}
double circle::circumference(void)
{
return (double) rad * 2 * 3.14;
}
double radius(int x1, int y1, int x2, int y2)
{
double rad = 0;
double xm, ym;
xm = (double)(x1 + x2) / 2;
ym = (double)(y1 + y2) / 2;
rad = sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
return rad;
}
int main(void)
{
double rad;
int x1, y1;
int x2, y2;
cout << "x1 : ";
cin >> x1;
cout << "y1 : ";
cin >> y1;
cout << "x2 : ";
cin >> x2;
cout << "y2 : ";
cin >> y2;
*circle one((double)radius(x1, y1, x2, y2));*
cout << fixed << one.area() << endl;
//cout << fixed << one.circumference() << endl;
return 0;
}
this is my code to calculate circle area and circumference.
But the problem is that when I initialize circle one, regardless of radius(x1, y1, x2, y2) value,
it always initialize to -9.2559631349317831e+061.
You don't initialise circle::rad here (instead you use local variable rad):
circle::circle()
{
double rad = 0;
}
circle::circle(double radius)
{
cout << radius << endl;
double rad = radius;
}
you should do something like:
circle::circle(): rad(0)
{
}
circle::circle(double radius): rad(radius)
{
}
double rad declares a local variable, which is not the same as the class member rad. The simplest fix:
circle::circle()
{
rad = 0;
}
circle::circle(double radius)
{
cout << radius << endl;
rad = radius;
}