Using nested structures and arrays Define a structure called %u201CPoint%u201D w
ID: 3539382 • Letter: U
Question
Using nested structures and arrays Define a structure called %u201CPoint%u201D which has int members x and y. Define another structure called %u201CTriangle%u201D which has three Point members. Write a function called distance that takes two Points and returns the distance between them. Write a main function that creates an array of three Triangles and asks the user for the x,y coordinates for the three points of each triangle. Then for each triangle, call the distance function to get the distances between its points and then print the perimeter of the triangle.
Here is my work so far,
#include <iostream> #include <iomanip> #include <cmath> using namespace std; struct Point { char Letter; int Ax; int Ay; int Bx; int By; }; struct Triangle
{
Point pointOne;
Point pointTwo;
Point pointThree;
}; void distance(Point); int main() { Point location; Point coordinates[3][3]; location.Letter = 'A'; cout << "Enter x: "; cin >> location.Ax; cout << "Enter y: "; cin >> location.Ay; location.Letter = 'B'; cout << "Enter x: "; cin >> location.Bx; cout << "Enter y: "; cin >> location.By; cout << "Point Location " << "A" << "(" << location.Ax << ", " << location.Ay << ");" << endl; cout << "Point Location " << "B" << "(" << location.Bx << ", " << location.By << ");" << endl; distance(location); for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { Point coordinates[i][j]; } } return 0; } void distance(Point d) { double value,dist; value = (d.Ax - d.Bx)*(d.Ax - d.Bx) + (d.Ay - d.By)*(d.Ay - d.By); dist = pow(value, 0.5); cout << " The distance between A and B is: " << dist << endl; }
Explanation / Answer
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
struct Point2D
{
int x;
int y;
};
struct Triangle
{
Point2D points[3];
};
double dist(Point2D , Point2D);
int main()
{
std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
std::cout.precision(2);
Triangle triangles[3];
for(int i=0;i<3;i++)
{
cout<<"Enter coordinates of Triangle "<<i+1<<endl;
for(int j=0;j<3;j++)
{
cout << "Enter x and y of point "<<j+1<<": ";
cin>>triangles[i].points[j].x >> triangles[i].points[j].y;
}
double perimeter = 0;
for(int j=0;j<3;j++)
{
perimeter = perimeter + dist(triangles[i].points[j],triangles[i].points[(j+1)%3]);
}
cout<<"Perimeter of triangle "<<i+1<<" is "<< perimeter<<endl<<endl;
}
return 0;
}
double dist(Point2D p1, Point2D p2)
{
double value,d;
value = (p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y);
d = sqrt(value);
return d;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.