dimanche 23 septembre 2018

More a mathematical question than a programming one . But since it needs to written in code . I have to find the two points of intersection

Given two circles with coordinates (x1, y1) and (x2, y2) with radius R1 and R2 to find the points or point of intersection , and whether the first circle is inside the second one or vice versa . After running the code and entering the coordinates I get wrong answers . The problem maybe with the formulas or with the code .

#include <iostream>
#include <cmath>
using namespace std;

int main(){
    int x, y, x1, y1, x2, y2 , R1, R2;
    cout << "enter the x coordinate of the first 
    circle: ";
    cin >> x1;
    cout << "enter the y coordinate of the first 
    circle: ";
    cin >> y1;
    cout << "enter the radius of the first circle: ";
    cin >> R1;
    cout << "enter the x coordinate of the second 
    circle: ";
    cin >> x2;
    cout << "enter the y coordinate of the second 
    circle: ";
    cin >> y2;
    cout << "enter the radius of the second circle: ";
    cin >> R2;



    double x2c = x2 - x1;
    double y2c = y2 - y1;
    double c = ((R2 * R2) - (R1 * R1) - (x2c * x2c) - 
    (y2c * y2c)) / 2 * x2c;
    double A = ((y2c * y2c) / (x2c * x2c)) + 1;
    double C = (c * c) - (R1 * R1);
    double B = 2 * C * (y2c / x2c);
    double d = sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - 
    y2) * (y1 - y2)));
    double D = B * B - 4 * A * C;

    if (d < R1 + R2){
    cout << "Circles Intersect" <<endl;
    float yi = ((-B + sqrt(D)) / 2 * A);
    float xi = ((C + (B + sqrt(D)) / 2 *A) * y2c) / 
    x2c;
    cout << "x and y coordinates of first point of 
    intersection intersection" << " " << xi << " " << 
    yi << endl;

    float xj = (-B - sqrt(D) /2 * A);
    float yj = ((C +(B - sqrt(D)) / 2 * A) * y2c) / 
    x2c;
    cout << "x and y coordinates of first point of 
    intersection intersection" << " " << xj << " " << 
    yj << endl;
    }
    else if (d == 0){
    cout << "circles are touching";
    float xi = ((C + (B + sqrt(D)) / 2 * A) * y2c) / 
    x2c;
    float yi = (-B + sqrt(D)) / 2 * A;
    cout << "x and y cordinates of touching point are 
    :" << " " << "(" << xi << "," << " " << yi << ")" 
    << endl;
    }
    else if (R2 > (R1 * d) && (R1 * d) < abs(R1 - R2)) 
    {
    cout << "1st circle is inside the second";
    }
    else if(R1 > (R2 * d) && (R2 * d) < abs(R1 - R2)){
    cout << "Second circle is inside the first";
    }
    else if (d > (R1 + R2)){
    cout << "circles do not intersect";
    }


    return 0;
}

enter code here

Aucun commentaire:

Enregistrer un commentaire