Jumat, 15 April 2011

Program C++ menghitung jarak titik A(x1,y1) dan B(x2,y2)


Algoritma :
Deskripsi
AB               : float
x1,x2,y1,y2     : float

Deklarasi
AB = sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2))
write (a,b)

Berikut programnya :

#include <iostream.h>
#include <conio.h>
#include <math.h>

class jarak {
friend istream& operator >> (istream&, jarak&);
friend ostream& operator << (ostream&, const jarak&);

public:
jarak();
void hitung(){
     AB = sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
};
private:
    float x1,y1,x2,y2;
    float AB;
};

jarak::jarak(){
cout << "mencari jarak antara titik A(x1,y1) dan B(x2,y2)\n" << endl;
}
istream& operator >>(istream& cin, jarak& masukan){
   cout << "Nilai titik A " <<endl;
   cout << "Masukkan nilai x1 : ";   cin >> masukan.x1;
   cout << "Masukkan nilai y1 : ";   cin >> masukan.y1;
   cout << "Nilai titik B " <<endl;
   cout << "Masukkan nilai x2 : ";   cin >> masukan.x2;
   cout << "Masukkan nilai y2 : ";   cin >> masukan.y2;
   cout<<endl;

return cin;
}
ostream& operator << (ostream& out, const jarak& keluaran)
{
  out<< "jarak antara titik tersebut adalah : " <<keluaran.AB<<endl;


return out;
}
void main(){
jarak titik;
cin>>titik;
titik.hitung();
cout<<titik;

getch();
}


Explanation:
In this program just like the program to find the midpoint of the program but find the distance between two points is point A (x1, y1) and point B (x2, y2). Here also using variable x1, x2, y1 and y2 but the difference only variable AB. To find the distance of two points by using the formula AB = sqrt ((x1-x2) ² + (y1-y2) ²). After getting input from the user initializes the program will work with the formula specified in the program.

0 komentar:

Posting Komentar

Template by:

Free Blog Templates