HI....
I'm doing this question...

Question

Using a non-void function with parameters, write a complete C++ program that prompts the user for the Cartesian coordinates of two points (x1, y1) and (x2, y2) and displays the distance between them computed using the formula:

distance = sqrt( (x1-x2)^2) + ((y1-y2)^2)...

and i came out with this code :

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


double distance(double x1,double x2,double y1,double y2);

int main () {

    cout<<"Enter The First Coordinate :";
    double x1,y1;
    cin>>x1>>y1;
    cout<<"Enter The Second Coordinate :";
    double x2,y2;
    cin>>x2>>y2;
    cout<<endl;

    cout<<"The Distance Between Two Coordinate Is :"<<distance(x1,x2,y1,y2);
}

double distance(double x1,double x2,double y1,double y2)
{
    return sqrt((2*(x1-x2))+(2*(y1-y2)));
}

this code run smoothly but not until it displayed the answer...
because when it display the distance,i always got the wrong answer and sometimes it display the NaN....

i dont know whats wrong with my code....
could somebody figure it out??

Thank You....

You wrote that

distance = sqrt( (x1-x2)^2) + ((y1-y2)^2).. .

and you are multiplying it by 2, instead of doing a power to 2. That is why you are getting a wrong answer.

double distance(double x1,double x2,double y1,double y2)
{
return sqrt((2*(x1-x2))+(2*(y1-y2)));
}

instead you should have

double distance(double x1,double x2,double y1,double y2)
{
return sqrt((pow((x1-x2),2))+(pow((y1-y2),2)));
}
:)

i think

sqrt((2*(x1-x2))+(2*(y1-y2))) and sqrt((pow((x1-x2),2))+(pow((y1-y2),2)))

are both same...

The simple math should be similar like this :

2^2 is just same like 2 * 2....both should be the same,so it should not cause any error...

:-O
yes, 2^2 is 2*2, but that is the only case :)

Note that 3^2 does not equal to 3*2 :)

Moreover, why would ^ be created if it's the same as *?? ;)

plus, when you are squaring something, you always get rid off the negative sign, however, if you multiply 2 by some negative number, you will get a negative number. And a negative number under a square root gives you a complex number. That is actually why you are getting the #IND as an answer.

haha...
i see that now...
i'm really careless did that assumption of 2^2 = 2*2..

Thank You afterall.. :)

haha...
i see that now...
i'm really careless did that assumption of 2^2 = 2*2..

Thank You afterall.. :)

This question has already been answered. Start a new discussion instead.