2012-12-02 94 views
0

我需要幫助完成作業。我生成了兩個平行數組來保存8個點的位置(一個保存x座標,一個保存y座標)。用戶然後輸入這些點的座標。我已經得到了我的代碼工作完全正常了這一點,但是這是我需要幫助:使用距離矩陣存儲點之間的距離並找到最近的鄰居

我必須計算每對點之間的距離,然後將距離存儲在一個二維數組。這樣做後,我必須逐行打印距離數組。

這樣做後,我必須再下一個使用距離矩陣(二維陣列)來找到每個點的最近鄰。

任何幫助表示讚賞,讓我知道如果我需要詳細說明任何事情。

這是我目前的代碼,我不知道從哪裏去。

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

distance = sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)); 

return distance; 
} 

int main() 
{ 
double xPoint[6]; 
double yPoint[6]; 
double matrix[6][6]; 

for(int i=0; i<6; i++) 
{ 
    cout << "Enter the x coordinate for position " << i << ": " << endl; 
    cin >> xPoint[i]; 
    cout << "Enter the y coordinate for position " << i << ": " << endl; 
    cin >> yPoint[i]; 
} 

for(int x =0; x<6; x++) 
{ 
    for(int y=0; y<6; y++) 
    { 
     matrix[x][y] = distance() 
    } 
} 

回答

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

/*double distance(double x1,double y1,double x2 ,double y2) 
{ 
double x; 

x= sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)); 

return x; 
} 
*/ 
int main() 
{ 
double xPoint[6]; 
double yPoint[6]; 
// double matrix[6][6]; 

for(int i=0; i<6; i++) 
    { 
cout << "Enter the x coordinate for position " << i << ": " << endl; 
cin >> xPoint[i]; 
cout << "Enter the y coordinate for position " << i << ": " << endl; 
cin >> yPoint[i]; 
} 

    for(int i=0; i<5; i++) 
    { 
    // for(int i=0; i<6; i++){ 
double X=sqrt(pow(xPoint[i+1]-xPoint[i],2)+pow(yPoint[i+1]-yPoint[i],2)); 

cout<<X<<" "; 
cout<<endl; 
// } 
} 
} 

你想這樣嗎?我可能不完全瞭解你的問題