[問題] 函式傳不回計算後的值

看板C_and_CPP (C/C++)作者 (沒有存在感的人)時間10年前 (2015/09/11 21:23), 編輯推噓0(006)
留言6則, 3人參與, 最新討論串1/2 (看更多)
開發平台(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

09/11 21:34, , 1F
踩到地雷.
09/11 21:34, 1F

09/11 21:35, , 2F
補上 Common_GetNorm 的宣告試試
09/11 21:35, 2F

09/11 21:37, , 3F
否則main.c會假設為Common_GetNorm(int,int) 然後就錯了
09/11 21:37, 3F

09/11 21:38, , 4F
阿,這樣就OK了,感謝,看來以後compile還是要加上-Wall
09/11 21:38, 4F

09/11 21:42, , 5F
應該是假設為 int Common_GetNorm()
09/11 21:42, 5F

09/11 21:53, , 6F
啊我記錯了,是假設回傳為int不是 不是參數int
09/11 21:53, 6F
文章代碼(AID): #1LyjNdhO (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1LyjNdhO (C_and_CPP)