Java版求斐波那契数
#include
#include
int Fib(int n)//递归
{
if (n <= 2){
return 1;
}
else
{
return Fib(n - 1) + Fib(n - 2);
}
}
int NFib(int n)//非递归
{
int a = 1, b = 1, c = 1;
if (n < 3){
return c;
}
else{
for (int i = 3; i <= n; i++){
c = a + b;
a = b;
b = c;
}
return c;
}
}
int main()
{
int n = 0;
scanf("%d", &n);
printf("第%d个斐波那契数为%d\n", n, Fib(n));//递归
printf("第%d个斐波那契数为%d\n", n, NFib(n));//非递归
system("pause");
return 0;
}
#include
#include
int Strlen(char *p)//递归
{
while (*p == '\0'){
return 0;
}
return 1 + Strlen(p + 1);
}
int NStrlen(char *p)//非递归
{
int ret = 0;
while ('\0' != *p){
p++;
ret++;
}
return ret;
}
int main()
{
char* p = "zxcvbnm";
printf("字符串的长度为%d\n", Strlen(p));//递归
printf("字符串的长度为%d\n", NStrlen(p));//非递归
system("pause");
return 0;
}
#include
#include
int Factoria(int n)//递归
{
if (1 == n){
return 1;
}
else{
return n* Factoria(n - 1);
}
}
int NFactoria(int n)//非递归
{
int i = 0;
int result = 1;
for (i = 1; i <= n; i++)
{
result *= i;
}
return result;
}
int main()
{
int n = 0;
scanf("%d", &n);
int ret1 = Factoria(n);//递归
int ret2 = NFactoria(n);//非递归
printf("%d的阶乘为%d\n", n, ret1);
printf("%d的阶乘为%d\n", n, ret2);
system("pause");
return 0;
}
#include
#include
void Print(int n)//递归
{
if (n > 9){
Print(n / 10);
}
printf("%d ", n%10);
}
int main()
{
int n = 0;
scanf("%d", &n);
Print(n);
system("pause");
return 0;
}
#include
#include
int Power(int n,int k)//递归
{
int ret = 0;
if ( k <2 ){
return n;
}
else
{
return n*Power(n, k - 1);
}
}
int main()
{
int n = 0, k = 0;
scanf("%d %d", &n, &k);
printf("%d的%d次方为%d\n",n,k, Power(n, k));
system("pause");
return 0;
}
#include
#include
int DigitSum(int n)//递归
{
if (n / 10 == 0)
{
return n;
}
else
{
return n % 10 + DigitSum(n / 10);
}
}
int main()
{
int n = 0;
scanf("%d", &n);
printf("%d\n", DigitSum(n));
system("pause");
return 0;
}
#include
#include
void Reverse(char *p)//递归
{
int len = strlen(p);
if (len <= 1){
return p;
}
else{
char tmp = p[0];
p[0]=p[len-1];
p[len - 1] = '\0';
Reverse(p + 1);
p[len - 1] = tmp;
}
}
int main()
{
char p[10] = "abcdefgh";
Reverse(p);
printf("%s\n", p);
system("pause");
return 0;
}