要死!!!3.29

1.递归和非递归分别实现求第n个斐波那契数。

此乃非递归

#include<stdio.h>
int fbnq(int n){
	int a = 1;
	int b = 1;
	int c = a;
	while (n > 2)	{
		c = a + b;
		a = b;
		b = c;
		n--;
	}
	return c;
}

int main(){
	int n = 0;
	scanf_s("%d", &n);
	int ret = fbnq(n);
	printf("第%d个斐波那契数为%d\n", n, ret);
	system("pause");
	return 0;
}

此乃递归

#include <stdio.h>
#include <stdlib.h>

int fib (int n) {
	if (n <= 2) {
		return 1;
	}
	else {
		return fib(n - 1) + fib(n - 2);
	}
}

int main() {
	int i = 0;
	int ret = 0;
	scanf_s("%d", &i);
	ret=fib(i);
	printf("第%d个菲薄是%d", i, ret);
	system("pause");
}


2.编写一个函数实现n^k,使用递归实现

#include <stdio.h>
#include <stdlib.h>

int nPowersOfk(int n, int k){
		return n*nPowersOfk(n, k - 1); 
}


int main(){
	int n = 3;
	int k = 3;	
	printf("%d\n", nPowersOfk(n, k));
	system("pause");
	return 0; }



3. 写一个递归函数DigitSum(n),输入一个非负整数,返回组成它的数字之和,
例如,调用DigitSum(1729),则应该返回1+7+2+9,它的和是19

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

int DigitSum(int n)
{
	int sum = 0;
	int m = 0;
	if (n != 0)
	{
		m = n % 10;
		n = n / 10;
		sum = m + DigitSum(n);
	}
	return sum;
}
int main()
{
	int x;
	printf("请输入: ");
	scanf("%d", &x);
	printf("各位数之和为:%d\n", DigitSum(x));
	system("pause");
	return 0;
}


4. 编写一个函数 reverse_string(char * string)(递归实现)
实现:将参数字符串中的字符反向排列。
要求:不能使用C函数库中的字符串操作函数。

#define  _CRT_SECURE_NO_WARNINGS


#define  _CRT_SECURE_NO_WARNINGS

#include<stdio.h>

#include<stdlib.h>

int   reverse_string(char * string){

	if (*string != '\0'){   

		string++;  



		reverse_string(string);

		printf("%c", *(string-1) );

	}

}

int main(){

	char* string = "abced";

	reverse_string(string);

	system("pause");

	return 0;

}


5.递归和非递归分别实现strlen

非递归

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

int changdu(char *str) {
	int count = 0;
	while (*str != '\0') {
		++count;
		++str;
	}
	return count;
}

int main() {
	char str[] = "abcdef";
	int ret=0;
	ret=changdu(str);
	printf("%d", ret);
	system("pause");
}

递归

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

int changdu(char *str) {
	if (*str != '\0') {
		return 1 + changdu(str + 1);
	}
	else {
		return 0;
	}
}

int main() {
	char str[] = "abcdef";
	int ret = 0;
	ret = changdu(str);
	printf("%d", ret);
	system("pause");
	return 0;
}


6.递归和非递归分别实现求n的阶乘

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

int jiecheng(int n) {
	int sum = 1;
	int i = 0;
	for (i = 1; i <= n; ++i){
		sum = sum*i;
	}
	return sum;
}

int digui(int n) {
	if (n == 0)

	{

		return 1;

	}
	return n*digui(n - 1);
}



int main() {
	int n = 5;
	int ret = 0;
	ret = digui(5);
	printf("%d", ret);
	system("pause");


7.递归方式实现打印一个整数的每一位

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

void print(int n) {

	if (n > 9) {
		print(n / 10);
	}
	printf("%d ", n % 10);
	
}

int main() {
	int num = 1234;
	print(num);
	system("pause");
	return 0;
	
}

猜你喜欢

转载自blog.csdn.net/nihuhui666/article/details/88896329