Answer to Question #255624 in C++ for khangphanana

Question #255624

Defines a struct that describes a point in 2D space. The values ​​of coordinates and coordinates are floats.

Write a function that calculates the distance of any 2 points

Write a function that changes the coordinates of a point.

Write a main program using the above functions.


1
Expert's answer
2021-10-23T13:53:08-0400
#include <iostream>
#include <math.h>
#include <time.h>
#include <stdlib.h>
using namespace std;
struct point{
    float x;
    float y;
};
float distance(struct point p1, struct point p2){
    return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}
void change(struct point& p1){
    float temp = p1.x;
    p1.x = p1.y;
    p1.y = temp;
}
int main(){
    srand(time(NULL));
    struct point p1 = {(float)(rand() % 10), (float)(rand() % 10)}, p2 = {(float)(rand() % 10), (float)(rand() % 10)};


    cout<<"Point 1 is ("<<p1.x<<", "<<p1.y<<")"<<endl;
    cout<<"Point 2 is ("<<p2.x<<", "<<p2.y<<")"<<endl;


    cout<<"Distance between point 1 and 2 is "<<distance(p1, p2)<<endl;
    cout<<"Changing coordinates of points...\n";


    change(p1);
    change(p2);
    cout<<"Point 1 is ("<<p1.x<<", "<<p1.y<<")"<<endl;
    cout<<"Point 2 is ("<<p2.x<<", "<<p2.y<<")"<<endl;


    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS