2016-04-23 56 views
3

如果我有這樣的結構:如何使用結構體作爲參數調用函數?

struct Point 
{ 
    double x; 
    double y; 
}; 

,並像一個函數這個

double geometricDistance(struct Point point1, struct Point point2) 
{ 
    double xDist = point1.x - point2.x; 
    double yDist = point1.y - point2.y; 
    return sqrt((xDist * xDist) + (yDist * yDist)); 
} 

當我打電話geometricDistance,我不能只是做geometricDistance(5,6);或類似的東西,因爲這是隻有兩個整數。我如何稱呼它?

感謝。

哦,是的,它在C方式。

明白了 - 使用大括號。謝謝。

回答

1

您必須傳遞一個類型爲struc Point的變量。

例如:

struct Point A; 
struct Point B; 
//add values in the fields x and y if you need to 
. 
. 
. 
double something = geometricDistance(A, B); 
4

所以,你有你的結構。

主要你可以聲明一個點。

struct Point point1; 
struct Point point2; 

現在您創建了一個名爲point的結構變量,它可以訪問結構中的double x和double y這兩個值。

point1.x = 12; 
point1.y = 15; 

point2.x = 5; 
point2.y = 6; 

要將它傳遞到您傳遞給結構的指針的函數中,該函數允許您編輯該點的值。 //函數調用 double value = geometricDistance(&point1, &point2);

double geometricDistance(struct Point* point1, struct Point* point2) 
{ 
    double xDist = point1->x - point2->x; 
    double yDist = point1->y - point2->y; 
return sqrt((xDist * xDist) + (yDist * yDist)); 
} 

編輯:我意識到,你實際上並不需要在指針結構來傳遞。你可以簡單地使函數參數double geometricDistance(struct Point point1, struct Point point2),因爲你沒有改變你聲明的任何結構變量的值。 你的函數調用可能僅僅是double value = geometricDistance(point1, point2);裏面的功能,而不是使用->參考,你可以使用.參考這樣point1.xpoint1.y

+1

通過'geometricDistance'返回的值是一個'double'不是'int'。 –

+0

有道理。謝謝。我現在看到爲什麼指針用於函數和結構。 – Josh

+1

您還更改了該功能的簽名。 要傳遞的參數是'struct Point',而不是'struct Point *'。 如果你想使用指針,你必須改變函數的主體,例如你必須使用'point1-> x'而不是point1.x –

1

有兩個其他類,你應該知道這也被稱爲「參數」。它們被稱爲「參數」,因爲它們定義了傳遞給函數的信息。

Actual parameters are parameters as they appear in function calls. 
Formal parameters are parameters as they appear in function declarations. 

定義/原型的功能geometricDistance表明它需要struct Point類型的兩個參數。您只需要使用struct point類型的兩個參數調用geometricDistance函數。

例如,

struct point a,b; 
. 
. 
double result = geometricDistance(a,b);