按照你的要求编写的返回逆序整数的递归的C语言程序如下(见图)
#include<stdio.h>
#include<math.h>
int reverse(int x){
int i=0
int y=x
while(y!=0){
y=y/10
i++
}
if(x<10){
return x
}else{
return x%10*pow(10,i-1)+reverse(x/10)
}
}
int main(){
printf("%d",reverse(123))
return 0
}
尾递归是一种混合了迭代和递归的算法,C语言代码如下:
/* 斐波那契数列的尾递归写法 */#include <stdio.h>
double fib(double n, double a, double b)
{
if(n<=0.0)
return -1.0 //错误输入
else if(n==1.0 || n==2.0)
return b //b记录最靠后的一项
else
{
while(n>2.0)
return fib(n-1.0, b, a+b)
}
}
int main(int argc, char *argv[])
{
double d, n = 20.0
d = fib(n, 1.0, 1.0)
printf("斐波那契数列第 %.f 项的值为 %.f。\n", n, d)
return 0
}