[英]Error encountered while defining a function to calculate the Euclidean distance between two points using a struct
我創建了一個 function 來計算 C 中兩點之間的歐幾里得距離(寫在 Codeblocks IDE 中),但是發生了一些錯誤:
error: expected ')' before 'p1'|
error: expected expression before ',' token|
上述錯誤發生在 function float Euclidean(struct point p1,struct point p2)
內部
下面是我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct point { float x, y, z; };
int main() {
struct point p1 = { 2.1, 3.0, 1.2 };
struct point p2 = { 0.5, 0.5, -0.2 };
float Euclidean(struct point p1, struct point p2);
return 1;
}
float Euclidean(struct point p1, struct point p2) {
float distance;
distance = (float)sqrt((float)powf((struct point p1[0] - struct point p2[0]), 2)+/n
(float)powf((struct point p1[1] - struct point p2[1]), 2)+/n
(float)powf((struct point p1[2] - struct point p2[2]), 2));
return distance;
printf("the distance between p1 and p2 is %.3f", distance);
};
我懷疑我的類型轉換存在一些問題,但我不知道為什么(我對 C 比較陌生)。 有人可以給我一些提示嗎?
提供的代碼中幾乎沒有錯誤。 您不需要將struct point
注釋添加到變量的使用中。 因此,無論您需要在哪里使用變量,都可以像Euclidean(p1, p2)
一樣直接引用它們
另一點是您需要在使用之前聲明/定義 function 。
要訪問結構中的值,請使用點表示法,而不是對其進行索引。 所以你需要使用p1.x
而不是p1[0]
。
return 之后的任何語句都不會運行,所以你的 print 語句不會在 function 中運行。
以下是在 GCC 9.3.0 中編譯和運行的更正代碼:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct point {float x, y, z; };
float Euclidean(struct point p1,struct point p2);
int main()
{
struct point p1 = {2.1,3.0,1.2};
struct point p2 = {0.5,0.5,-0.2};
float distance = Euclidean(p1, p2);
return 0;
}
float Euclidean(struct point p1,struct point p2){
float distance;
distance = (float)sqrt((float)pow((p1.x-p2.x),2)+
(float)pow((p1.y-p2.y),2)+
(float)pow((p1.z-p2.z),2));
printf("the distance between p1 and p2 is %.3f\n",distance);
return distance;
};
正如另一個答案中所說,如果您從某本書中了解 C 語法的基礎知識會很好。
除了@e_a好答案...
...而不是使用double
函數來解決float
問題,而是使用float
函數。 放下鑄件。
//float distance;
//distance = (float)sqrt((float)pow((p1.x-p2.x),2)+
// (float)pow((p1.y-p2.y),2)+
// (float)pow((p1.z-p2.z),2));
float distance = sqrtf(powf((p1.x - p2.x),2) +
powf((p1.y - p2.y),2) +
powf((p1.z - p2.z),2));
您的主要問題是缺乏 C 語言的基本知識。
distance = sqrt((powf((p1.X-p2.X),2)+
powf((p1.Y-p2.Y),2)+
powf((p1.Z-p2.Z),2));
我寧願建議從好的 C 書開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.