解释下面递归函数的功能。
null
问题1
C++
void fun1( int n) { int i = 0; if (n > 1) fun1(n - 1); for (i = 0; i < n; i++) cout << " * " ; } // This code is contributed by shubhamsingh10 |
C
void fun1( int n) { int i = 0; if (n > 1) fun1(n-1); for (i = 0; i < n; i++) printf ( " * " ); } |
JAVA
static void fun1( int n) { int i = 0 ; if (n > 1 ) fun1(n - 1 ); for (i = 0 ; i < n; i++) System.out.print( " * " ); } // This code is contributed by shubhamsingh10 |
蟒蛇3
def fun1(n): i = 0 if (n > 1 ): fun1(n - 1 ) for i in range (n): print ( " * " ,end = "") # This code is contributed by shubhamsingh10 |
C#
static void fun1( int n) { int i = 0; if (n > 1) fun1(n-1); for (i = 0; i < n; i++) Console.Write( " * " ); } // This code is contributed by shubhamsingh10 |
Javascript
<script> function fun1(n) { let i = 0; if (n > 1) fun1(n - 1); for (i = 0; i < n; i++) document.write( " * " ); } // This code is contributed by gottumukkalabobby </script> |
答:打印的星星总数等于1+2+…。(n-2)+(n-1)+n,也就是n(n+1)/2。
问题2
C++
#define LIMIT 1000 void fun2( int n) { if (n <= 0) return ; if (n > LIMIT) return ; cout << n << " " ; fun2(2*n); cout << n << " " ; } // This code is contributed by shubhamsingh10 |
C
#define LIMIT 1000 void fun2( int n) { if (n <= 0) return ; if (n > LIMIT) return ; printf ( "%d " , n); fun2(2*n); printf ( "%d " , n); } |
JAVA
int LIMIT = 1000 ; void fun2( int n) { if (n <= 0 ) return ; if (n > LIMIT) return ; System.out.print(String.format( "%d " , n)); fun2( 2 * n); System.out.print(String.format( "%d " , n)); } |
蟒蛇3
LIMIT = 1000 def fun2(n): if (n < = 0 ): return if (n > LIMIT): return print (n, end = " " ) fun2( 2 * n) print (n, end = " " ) # This code is contributed by shubhamsingh10 |
C#
int LIMIT = 1000 void fun2( int n) { if (n <= 0) return ; if (n > LIMIT) return ; Console.Write(n+ " " ); fun2(2*n); Console.Write(n+ " " ); } // This code is contributed by Shubhamsingh10 |
Javascript
<script> let LIMIT = 1000; function fun2(n) { if (n <= 0) return ; if (n > LIMIT) return ; document.write(n + " " )); fun2(2 * n); document.write(n + " " )); } // This code is contributed by gottumukkalabobby </script> |
答:对于正n,fun2(n)打印n、2n、4n、8n……的值,而该值小于极限。按递增顺序打印值后,它会按相反顺序再次打印相同的数字。例如,fun2(100)打印100、200、400、800、800、400、200、100。 如果n为负,则立即返回函数。 如果您发现任何答案/代码不正确,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END