0
点赞
收藏
分享

微信扫一扫

蓝桥杯第六届c++大学B组详解

一ke大白菜 04-08 20:00 阅读 0

函数的声明

(main函数前)----告诉有一个函数

格式:  类型 函数名(参数);

函数的声明 放到头文件add.c

函数的定义

----创建函数----放到add.c

格式:类型 函数名(参数)

{

语句项;

}

在文件中包含头文件

#include "add.h"

包含头文件-实质上就拷贝头文件的声明 到文件

导入静态库

#pragma comment (lib, "add.lib")

函数的递归

例1: 输入无符号整形unsigned int数,打印每一位print 

%u 打印无符号整形数

#include<stdio.h>
void print(unsigned int n)
{
	if (n > 9)
	{
		print(n / 10);
	}
	printf("%d ", n % 10);
}

int main()
{
	unsigned int n = 0;
	scanf("%u", &n);
	print(n);

	return 0;
}

例2: 函数不允许创建临时变量,求字符串长度my_strlen

1.有临时变量

#include<stdio.h>

void my_strlen(char* str)
{
	int count = 0;
	while (*str != '\0')
	{
		count++;
		str++;
	}
	printf("%d\n", count);
}

int main()
{
	char str[] = "abcdef";
	my_strlen(&str);
	return 0;
}

2.无临时变量--递归

#include<stdio.h>

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

int main()
{
	char str[] = "abcdef";
	printf("%d\n", my_strlen(&str));
	return 0;
}

例3: 不考虑溢出, 求N的阶乘fac()

1.递归

//1.递归
#include <stdio.h>

int Fac(int n)
{
	if (n == 1)
		return 1;
	else
	{
		return n*Fac(n-1);
	}
}

int main()
{
	int n = 0;
	scanf("%d", &n);
	printf("%d\n", Fac(n));
	return 0;
}

2.迭代--循环

//非递归
#include <stdio.h>

int main()
{
	int n = 0;
	int fac = 1;
	scanf("%d", &n);
	if (n == 1)
		fac = 1;
	while (n > 1)
	{
		fac = n * fac;
		n--;
	}
	
	
	printf("%d\n", fac);
	return 0;
}

例4: 不考虑溢出, 求斐波那契数列Fib()

1.递归

//递归
#include<stdio.h>

int Fib(int n)
{
	if (n == 1 || n == 2)
		return 1;
	else
		return Fib(n - 1) + Fib(n - 2);
}

int main()
{
	int n = 0;
	scanf("%d", &n);
	printf("%d\n", Fib(n));
	return 0;
}

2.非递归

//2.非递归
#include <stdio.h>
int main()
{
	int a = 1;
	int b = 1;
	int fib = 1;
	int n = 0;
	scanf("%d", &n);
	if (n == 1 | n == 2)
		fib = 1;
	while (n > 2)//5
	{
		fib = a + b;
		a = b;
		b = fib;
		n--;
	}
	printf("%d\n", fib);
	return 0;
}

函数在调用过程中重复过多,使用非递归

举报

相关推荐

0 条评论