2012-10-30 65 views
-1

我是C++的新手,不確定如何將參數傳遞給函數。需要幫助理解傳遞參數到函數

我正在使用函數Distance()來計算兩個節點之間的距離。 我聲明函數是這樣的:

int Distance(int x1, int y1, int x2 , int y2) 
{ 
    int distance_x = x1-x2; 
    int distance_y = y1- y2; 
    int distance = sqrt((distance_x * distance_x) + (distance_y * distance_y)); 
    return distance; 
} 

在主存儲器我有2個for循環。 我需要知道的是,如果我可以通過像這樣的值:Distance (i, j, i+1, j+1)

for(int i = 0; i < No_Max; i++) 
{ 
    for(int j = 0; j < No_Max; j++) 
    { 
     if(Distance(i, j, i+1, j+1) <= Radio_Range) // the function 
      node_degree[i] = node_degree[i] + 1; 

     cout << node_degree[i] << endl; 
    } 
} 
+4

對我來說很好。有沒有理由認爲它不正確? – john

+0

爲了得到更準確的距離值,你的函數應該返回一個浮點類型,比如'double'。 –

+0

您可能不想像'sqrt'那樣將'sqrt'的結果轉換爲'int'。 – aschepler

回答

3

函數的參數可以作爲與該參數的類型匹配或可以轉換的任何表達式提供。

2

看起來好像你正確調用你Distance(int, int, int, int)功能: 如果要使用開方你應該使用int的雙代替。 下面的語句將調用Distance()

Distance (i, j, i+1, j+1); 

這將存儲由Distance()在變量返回的值:

int dist = Distance (i, j, i+1, j+1); 

這會比較受Distance()(左操作數)Radio_Range返回的值(正確的操作數)。如果左操作數小於或等於右操作數,則它的計算結果爲1(true)。否則它將是0(false)。如果if語句內的總體表達值是緊隨if語句將被執行非零,語句或塊:

if(Distance(i, j, i+1, j+1) <= Radio_Range) 
    //Statement; 

或:

if(Distance(i, j, i+1, j+1) <= Radio_Range){ 
    //Statement; 
    //Statement; 
    //... 
} 

然而,返回的值由Distance()將被截斷爲一個整數。因此,distance將不等於實際距離,除非(distance_x * distance_x) + (distance_y * distance_y)是一個完美的正方形。爲了獲得更好的精度,請考慮使用double。如果您打算將函數返回一個int,明智的做法是做一個明確的類型轉換,如:

int distance = (int)sqrt((distance_x * distance_x) + (distance_y * distance_y)); 

這將確保,如果你或其他人看的代碼以後,就不會認爲函數使用了錯誤的數據類型。