Re: [問題] 求倍數(使用遞迴)

看板C_and_CPP (C/C++)作者 (喲)時間15年前 (2011/03/30 22:12), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/3 (看更多)
※ 引述《qoo200033 (好時光)》之銘言: : 問題:寫出一個可以計算1~100中是7的倍數的函式,若為7的倍數則傳回main()中印出 : 程式碼 : #include<stdio.h> : int multiple(int); : int main(void){ : int result,i=1; : result=multiple(i); : printf("%d is 7 multiple\n",result); : return 0; : } : int multiple(int i){ : if (i==100) : return (0); : else{ : if (i%7==0) : return i; : } multiple(i+1); : } : 答案永遠都只有一個,請問各位高手在遞迴的部分要怎麼寫比較好 要有一個結構或物件變數收集計算結果: struct List { int head; struct List *tail; }; struct List* multiple(int from) { struct List *result; if (from > 100) return NULL; if (from % 7 == 0) { result = (struct List*)malloc(sizeof(struct List*)); result->head = from; result->tail = multiple(from + 1); return result; } else { return multiple(from + 1); } } 但按照題目和你的寫法,要這樣玩也可以: #include<stdio.h> int multiple(int); int main(void){ int i=1; i = multiple(i); while ( i >= 1 && i <= 100) { printf("%d is 7 multiple\n", i); i = multiple(i + 1); } return 0; } int multiple(int i){ if (i==100) return (0); else{ if (i%7==0) return i; } multiple(i+1); } -- /yau -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.160.114.217 ※ 編輯: yauhh 來自: 218.160.114.217 (03/30 22:15)

03/30 22:19, , 1F
這是遞迴嗎 Q_O
03/30 22:19, 1F
文章代碼(AID): #1Dapf7l4 (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1Dapf7l4 (C_and_CPP)