2017-10-06 50 views
-2

给定以下系列:1,2,5, 26,677, .....使得该系列的第n项等于 (n-1)th^2 +1并且该系列的第一项是1. 使用名为f的递归函数编写程序来计算第n期。使用循环打印系列中前n个项的f 的值。你将从用户那里获得输入n。给定以下系列...系列的第n项等于(n-1)th^2 +1并且系列的第一项是1使用递归

任何人都可以帮我弄清楚我到底在做什么?我不知道如何用递归来做到这一点,我知道如何做到这一点。

感谢, 牛逼

编辑:我知道了做序列现在,我只是不知道如何解决它那里是一个for循环,做的第一件5这个序列然后递归函数没有休息:

#include <stdio.h> 
#include <math.h> 

double f(double n); 

int main(){ 
/* 
    Problem 6: 
    - Recursive function to generate nth term of f(x) 
*/ 

double nth; 
int i = 0,flag=1; 
double result; 
int seq[] = {1,2,5,26,677}; 

printf("Please enter the number of terms you would like to generate: 

\n"); 

    while(flag == 1){ 
     if(scanf("%lf",&nth) == 1){ 
      flag = 0; 
     } 
     else{ 
      printf("Invalid number, program is exiting...\n"); 
      return 0; 
     } 
    } 

    result = f(nth); 

    return 0; 
} 


double f(double n){ 
    // base condition 
    if(n == 1) 
     return 1; 
    else 
     printf("(%.0lf)",pow(f(n-1),2.0) + 1); 
} 
+0

开始你已经尝试过的东西。 –

+0

该规则是以递归方式编写的。这就像将它复制并粘贴到你的函数中一样。 –

+0

你能告诉我如何实现它吗?我不确定我明白递归的样子。@EugeneSh。 – tidwellxyz

回答

1

你能做到在同一行

#include <stdio.h> 

size_t f(size_t nth) { 
    return nth == 1 ? 1 : f(nth - 1) * f(nth - 1) + 1; 
} 

int main() { 
    printf("%zu", f(5)); 
    return 0; 
} 
+0

我刚刚用我找到的解决方案编辑它,但我无法获得前5个数字的for循环。任何想法? – tidwellxyz

相关问题