我想寫一個程序來近似pi。它基本上採用0.00到1.00之間的隨機點,並將它們與圓的邊界進行比較,並且圓內的點與總點的比值應接近pi(這是一個非常快速的解釋,規範深入得多)。C編程 - 「未定義的符號在文件中引用」
Undefined first referenced
symbol in file
pow /var/tmp//cc6gSbfE.o
ld: fatal: symbol referencing errors. No output written to a.out
collect2: ld returned 1 exit status
這有什麼情況發生:
然而,用gcc編譯的時候我收到以下錯誤?我從來沒有見過這個錯誤,我不知道它爲什麼會出現。這裏是我的代碼(雖然我沒有經過充分測試它,因爲我不能讓過去的錯誤):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void) {
float x, y;
float coordSquared;
float coordRoot;
float ratio;
int n;
int count;
int i;
printf("Enter number of points: ");
scanf("%d", &n);
srand(time(0));
for (i = 0; i < n; i++) {
x = rand();
y = rand();
coordSquared = pow(x, 2) + pow(y, 2);
coordRoot = pow(coordSquared, 0.5);
if ((x < coordRoot) && (y < coordRoot)) {
count++;
}
}
ratio = count/n;
ratio = ratio * 4;
printf("Pi is approximately %f", ratio);
return 0;
}
請注意,不要使用'pow(x,2)',使用'x * x'。更簡單,更快速。 –