看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Linux 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 我寫了一個函式想計算一個陣列的平方和開根號 可是卻傳不回正確的值 餵入的資料(Input): 引數為一個float pointer 跟該陣列含有的元素個數 預期的正確結果(Expected Output): 該陣列平方和開根號 錯誤結果(Wrong Output): 奇怪的值 程式碼(Code):(請善用置底文網頁, 記得排版) Common.c: #include <math.h> float Common_GetNorm(float* var, unsigned int n) { int i; double sum = 0.f; for (i=0; i<n; ++i) { sum += var[i]*var[i]; } return sqrtf(sum); } main.c: #include <stdio.h> int main(void) { float acc[3]; acc[0] = 0.01; acc[1] = 0.01; acc[2] = 1.01; float a = Common_GetNorm(acc, 3); printf("%f\n", a); } 補充說明(Supplement): gcc Common.c main.c -lm -o test ./test 正確答案是1.010099 我用RPi得到的值卻是-1095711232.000000 用筆電跑出來為3.0000000 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 90.27.40.85 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1441977831.A.AD8.html
Feis: 踩到地雷. 09/11 21:34
bibo9901: 補上 Common_GetNorm 的宣告試試 09/11 21:35
bibo9901: 否則main.c會假設為Common_GetNorm(int,int) 然後就錯了 09/11 21:37
wtchen: 阿,這樣就OK了,感謝,看來以後compile還是要加上-Wall 09/11 21:38
Feis: 應該是假設為 int Common_GetNorm() 09/11 21:42
bibo9901: 啊我記錯了,是假設回傳為int不是 不是參數int 09/11 21:53