iT邦幫忙

2

遞迴遇到問題

題目:
使用 recursive 完成 F(), 輸入 n,計算1~n的偶數總和
int F(int);
int F(//自行完成) {
}

我的CODE:
#include
using namespace std;
int F(int n);

int main()
{
int n;
cin>>n;
F(n);
return 0;
}

int F(int n){
int sum=0;
if(n==2)
return n;
else if(n==0)
return n;
else if(n==1)
return 0;
else if(n%2==0) //若偶數
return sum=F(n-2)+n;
else if(n%2!=0) //若奇數
return sum=F(n-1);
}

結果它跑不出來ˊˇˋ

淺水員 iT邦大師 6 級 ‧ 2019-11-17 16:23:09 檢舉
1. 沒輸出
2. 「------//若奇數」不確定是不是真的這樣寫,註解不能這樣寫
3. 如其他人所言,使用者輸入負數會有問題。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

4
小魚
iT邦大師 1 級 ‧ 2019-11-17 17:50:57
最佳解答

看起來沒太大問題,
我猜你是不是忘了cout了!?
而且前面的include不見了.
我稍微修改了一下.

#include <iostream>
using namespace std;
int F(int n);

int main()
{
	int n;
	cout << "請輸入數字: ";
	cin >> n;
	cout << "結果: " << F(n) << endl;
	system("pause");
	return 0;
}

int F(int n) {
	if (n < 0)
		return -1;
	else if (n == 0)
		return n;
	else if (n % 2 == 0) //若偶數
		return F(n - 2) + n;
	else if (n % 2 != 0) //若奇數
		return F(n - 1);
}

COUT 冏

真的餒 忘記Cout @@
感謝你的修正
剛剛真的看到快脫窗

0
阿展展展
iT邦好手 1 級 ‧ 2019-11-17 16:02:36
  1. 跑不出來大概是無窮迴圈
  2. else if(n==0) 你的這個樣子寫法 可能有點問題

我要發表回答

立即登入回答