编写递归函数 [英] Writing recursive functions
问题描述
我在编写递归函数时遇到麻烦。
I'm having trouble with writing recursive functions.
三角数如下:
1 = 1
3 = 1 + 2
3 = 1 + 2
6 = 1 + 2 + 3
6 = 1 + 2 + 3
10 = 1 + 2 + 3 + 4
10 = 1 + 2 + 3 + 4
15 = 1 + 2 + 3 + 4 + 5
15 = 1 + 2 + 3 + 4 + 5
21 = 1 + 2 + 3 + 4 + 5 + 6
21 = 1 + 2 + 3 + 4 + 5 + 6
等。
该系列以1(第一个三角数)开头。为了计算第n个三角数,n为
加到前一个三角数上。例如,通过将第三个三角数加4(即6)来计算第四个三角数
,即10 =(1 + 2 + 3)+ 4。
The series begins with 1 (the first triangular number). To calculate the nth triangular number, n is added to the previous triangular number. For example, the fourth triangular number is calculated by adding 4 to the third triangular number (which is 6), i.e. 10 = (1 + 2 + 3) + 4.
到目前为止,这是我想出的:
So far, this is what I've come up with:
int triNum(n)
{
if (n<=1)
return n;
int num = 0;
for (int i = 0; i < n; i++)
{
num = n + triNum(n-1)
}
return num;
}
但是我不确定这是否是正确的答案,任何人都可以帮忙指导我如何解决此问题?
However I'm not sure that this is the correct answer, can anyone help guide me how I should approach this problem?
推荐答案
这会产生所需的输出:
int tri(int n) {
if (n < 1) return 1;
return (n+1) + tri(n-1);
}
您可以像这样测试它:
int main(void){
for (int i=0; i<10; i++) {
printf("%d: %d\n",i,tri(i));
}
return 0;
}
这篇关于编写递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!