[問題] 全域變數在遞迴裡執行結果

看板C_and_CPP作者 (ptes93041)時間10年前 (2013/09/16 19:01), 編輯推噓0(007)
留言7則, 4人參與, 最新討論串1/1
小弟最近開始寫一個題目為質因數分解,有宣告一個全域變數要讓遞迴一直降低測資的值 ,可是只有在遞迴裡時值才會變,讓我百思不得其解,想請板上高手指導,以下為程式碼。 #include<stdio.h> #include<stdlib.h> int a=0;//此行為輸入測資之全域變數,在進行下面遞迴處理時假設測資為12,只有在 static int count;//遞迴裡a才會減少,當return時進入下一個for此時a又再回到12 int main() { int th(int x,int y); int i,temp=0; scanf("%d",&a); printf("%d=",a); for(i=2;i<=a;i++) { if(a==1) break; temp=th(a,i); if(temp==1) printf("%d*",i); else if(temp!=0) printf("%d^%d*",i,temp); count=0; } system("pause"); return 0; } int th(int a,int b) { if((a%b)==0) { count++; a=(a/b); return th(a,b); } return count; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.126.50.174

09/16 19:12, , 1F
因為 th 的 a 不是全域,你在參數宣告另一個了
09/16 19:12, 1F

09/16 19:27, , 2F
用指標(pointer)或參考(reference)傳遞參數也可以
09/16 19:27, 2F

09/16 19:28, , 3F
local優先於global喔
09/16 19:28, 3F

09/16 19:59, , 4F
我把th的int a改成a之後出來的結果還是一樣錯的
09/16 19:59, 4F

09/16 20:00, , 5F
所以這題要用這個寫法的話要改用指標嗎
09/16 20:00, 5F

09/16 20:10, , 6F
如果你要玩全域就直接把參數的a拿掉啦,改成a要幹嘛zz
09/16 20:10, 6F

09/16 20:19, , 7F
感謝ck大不勝其煩解答我的問題,已成功感謝
09/16 20:19, 7F
文章代碼(AID): #1IDkKEWN (C_and_CPP)