目录
1.函数的定义和分类
1.在维基百科中,对函数的定义是子程序。
(1)在计算机科学中,子程序(英语:Subroutine, procedure, function, routine, method, subprogram, callable unit),是一个大型程序中的某部分代码, 由一个或多个语句块组成。它负责完成某项特定任务,而且相较于其他代码,具备相对的独立性。
(2)一般会有输入参数并有返回值,提供对过程的封装和细节的隐藏。这些代码通常被集成为软件库。
2.C语言中的函数分类
1.库函数
2.自定义函数
2.库函数
为什么会有库函数?1. 我们知道在我们学习C语言编程的时候,总是在一个代码编写完成之后迫不及待的想知道结果,想把这个结果打印到我们的屏幕上看看。这个时候我们会频繁的使用一个功能:将信息按照一定的格 式打印到屏幕上(printf)。
2. 在编程的过程中我们会频繁的做一些字符串的拷贝工作(strcpy)。
3. 在编程是我们也计算,总是会计算n的k次方这样的运算(pow)。
像上面我们描述的基础功能,它们不是业务性的代码。我们在开发的过程中每个程序员都可能用的到,为了支持可移植性和提高程序的效率,所以C语言的基础库中提供了一系列类似的库函数,方便程序员进行软件开发。
注:库函数的使用必须包含#include对应的头文件。
这里有两个推荐学习的网站:cppreference.com;www.cplusplus.com - The C++ Resources Network那怎么学习库函数呢?这里我们简单的看看: www.cplusplus.com
这是C语言的库,我们在左边的部分可以很快地找到我们是使用过的函数,
我将用一个例子学习库函数。
strcpy这个函数包含在string.h这个头文件里面,这个函数的参数需要两个指针,返回值是一个字符型指针,指针就是地址,char* strcpy(char * destination, const char * source);
char * strcpy ( char * destination, const char * source );
Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).
翻译:将源头(source)指向的C字符串复制到目的地(destination)指向的数组中,包括终止空字符(并在该点停止).包括‘\0’字符。
To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.
翻译:为了避免溢出,destination指向的数组的大小应该足够长,以包含与source相同的C字符串(包括终止空字符),并且不应该在内存中与source重叠。
Pointer to the destination array where the content is to be copied.
指向要复制内容的目标数组的指针.
C string to be copied.
要复制的c字符串。
返回值是destination, destination是一个字符型指针。
总结一句话,就是strcpy函数是将一个字符串复制到另一个字符串上去。
2.1 以下是几个例子
eg1: strlen 计算字符串长度
需要调用头文件 - <string.h>
//strlen #include<stdio.h> #include<string.h> int main() { char arr[] = "abc"; int len = strlen(arr);//size_t->unsigned int printf("%d\n", len); return 0; }
eg2 上面strlen的标准写法
#include<stdio.h> #include<string.h> int main() { char arr1[] = "abc"; //size_t -> unsigned int size_t len = strlen(arr1); //%d - 有符号数 //%u - 无符号数 printf("%u\n", len); return 0; }
eg3 memset - 修改字符
需要调用头文件 - <string.h>
#include<stdio.h> #include<string.h> int main() { char arr[] = "hello world"; //memset(指针指向的目的地,设置的字符,修改多少个字符) memset(arr, 'x', 5); printf("%s\n", arr); return 0; }
输出结果:
eg4 strcpy - 复制字符串
需要调用头文件 - <string.h>
#include<stdio.h> #include<string.h> int main() { char arr1[20] = { 0 };//目的地 char arr2[] = "hello world";//源数据 strcpy(arr1, arr2); printf("%s\n", arr1); return 0; }
输出结果:
3. 自定义函数
函数的组成:ret_type fun_name ( para1 , * ){statement ; // 语句项}ret_type 返回类型fun_name 函数名para1 函数参数举一个栗子:写一个函数可以找出两个整数中的最大值。#include <stdio.h> //get_max函数的设计 int get_max(int x, int y) { return (x>y)?(x):(y); } int main() { int num1 = 10; int num2 = 20; int max = get_max(num1, num2); printf("max = %d\n", max); return 0; }
再举个栗子:写一个函数可以交换两个整形变量的内容。#include <stdio.h> //实现成函数,但是不能完成任务 void Swap1(int x, int y) { int tmp = 0; tmp = x; x = y; y = tmp; } //正确的版本 void Swap2(int *px, int *py) { int tmp = 0; tmp = *px; *px = *py; *py = tmp; } int main() { int num1 = 1; int num2 = 2; Swap1(num1, num2); printf("Swap1::num1 = %d num2 = %d\n", num1, num2); Swap2(&num1, &num2); printf("Swap2::num1 = %d num2 = %d\n", num1, num2); return 0; }
在Swap1函数里面虽然交换了两个数的内容,但是这是形参,出了这个函数区域就会自动销毁,所以并不能改变这两数的值。
在Swap2函数里面,用传址调用,可以交换这两个数的值。
4. 函数的参数
4.1 实际参数(实参):
真实传给函数的参数,叫实参。实参可以是: 常量、变量、表达式、函数等 。无论实参是何种类型的量,在进行函数调用时,它们都必须有确定的值,以便把这些值传送给形参。
4.2 形式参数(形参):
形式参数是指 函数名后括号中的变量 ,因为形式参数只有在函数被调用的过程中才实例化(分配内存单元),所以叫 形式参数 。形式参数当函数调用完成之后就自动销毁了。因此形式参数只在函数中有效。上面 Swap1 和 Swap2 函数中的参数 x , y , px , py 都是 形式参数 。在 main 函数中传给 Swap1 的 num1, num2 和传给 Swap2 函数的 &num1 , &num2 是 实际参数 。
代码对应的内存分配如下:
5. 函数的调用:
5.1 传值调用
函数的形参和实参分别占有不同内存块,对形参的修改不会影响实参。5.2 传址调用
传址调用是把函数外部创建变量的内存地址传递给函数参数的一种调用函数的方式。这种传参方式可以让函数和函数外边的变量建立起真正的联系,也就是函数内部可以直接操作函数外部的变量。5.3 练习
1. 写一个函数可以判断一个数是不是素数。2. 写一个函数判断一年是不是闰年。3. 写一个函数,实现一个整形有序数组的二分查找。4. 写一个函数,每调用一次这个函数,就会将 num 的值增加1。
#include<stdio.h>
#include<math.h>
//is_prime
//是素数返回1,不是素数返回0
int is_prime(int n)
{
//2~n-2的数字试除
int j = 0;
//for (j = 2; j < n; j++)
for (j = 2; j < sqrt(n); j++)
{
if (n % j == 0)
{
return 0;
}
}
return 1;//素数
}
int main()
{
int i = 0;
for (i = 100; i <= 200; i++)
{
//判断i是否为素数 如果i是素数就打印i
if (is_prime(i) == 1)
{
printf("%d ", i);
}
}
return 0;
}
2.判断闰年
#include<stdio.h>
int is_leap_year(int y)
{
if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0))
return 1;
else
return 0;
//return (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0));
}
int main()
{
int y = 0;
int count = 0;//计数器
for (y = 1000; y <= 2000; y++)
{
//判断y是不是闰年
if (is_leap_year(y) == 1)
{
count++;
printf("%d ", y);
}
}
printf("\ncount = %d\n", count);
return 0;
}
3.实现有序数组的二分查找
//二分查找
#include<stdio.h>
//数组arr传给binary_search()函数的时候,其实传递的是数组arr首元素地址
//找到了就返回下标
//找不到返回-1
int binary_search(int arr[], int k, int sz)
{
int left = 0;
int right = sz - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (arr[mid] < k)
{
left = mid + 1;
}
else if(arr[mid] > k)
{
right = mid - 1;
}
else
{
return mid;
}
}
return -1;//找不到
}
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int key = 7;
int sz = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", sz);
int ret = binary_search(arr, key, sz);
if (-1 == ret)
{
printf("找不到\n");
}
else
{
printf("找到了,下标是%d\n", ret);
}
return 0;
}
4.每调用一次函数,num加一
//1
#include<stdio.h>
void add(int* p)
{
*p = *p + 1;
}
int main()
{
int num = 0;
add(&num);
printf("%d\n", num);
add(&num);
printf("%d\n", num);
return 0;
}
//2
#include<stdio.h>
int add(int n)
{
n++;
return n;
}
int main()
{
int num = 0;
num = add(num);
printf("%d\n", num);
return 0;
}
6. 函数的嵌套调用和链式访问
函数和函数之间可以根据实际的需求进行组合的,也就是互相调用的。
6.1 嵌套调用
#include <stdio.h>
void new_line()
{
printf("hehe\n");
}
void five_line()
{
int i = 0;
for(i=0; i<5; i++)
{
new_line();
}
}
int main()
{
five_line();
return 0;
}
//打印5行hehe
6.2 链式访问
把一个函数的返回值作为另外一个函数的参数。strlen(arr) - 求arr字符串长度strcat(str1, str2) - 将str2 字符串追加到str1;
#include <stdio.h>
#include <string.h>
int main()
{
char arr[20] = "hello";
int ret = strlen(strcat(arr,"bit"));//这里介绍一下strcat函数
printf("%d\n", ret);
return 0;
}
//打印:
//8
#include <stdio.h>
int main()
{
printf("%d ", printf("%d ", printf("%d ", 43)));
//结果是啥?
//注:printf函数的返回值是打印在屏幕上字符的个数
return 0;
}
//打印:
//43 2 1
7. 函数的声明和定义
7.1 函数声明:
1. 告诉编译器有一个函数叫什么,参数是什么,返回类型是什么。但是具体是不是存在,函数声明决定不了。2. 函数的声明一般出现在函数的使用之前。要满足先声明后使用。3. 函数的声明一般要放在头文件中的。
7.2 函数定义:
#ifndef __TEST_H__#define __TEST_H__// 函数的声明int Add ( int x , int y );#endif //__TEST_H__
#include "test.h"// 函数 Add 的实现int Add ( int x , int y ){return x + y ;}
8. 函数递归
8.1 什么是递归?
程序调用自身的编程技巧称为 递归( recursion) 。递归做为一种算法在程序设计语言中广泛应用。 一个过程或函数在其定义或说明中有直接或间接调用自身的一种方法,它通常把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解,递归策略 只需少量的程序就可描述出解题过程所需要的多次重复计算,大大地减少了程序的代码量。递归的主要思考方式在于:把大事化小8.2 递归的两个必要条件
存在限制条件,当满足这个限制条件的时候,递归便不再继续。每次递归调用之后越来越接近这个限制条件。8.2.1 练习 1 :接受一个整型值(无符号),按照顺序打印它的 每一位 。例如:输入: 1234 ,输出 1 2 3 4.参考代码:#include <stdio.h> void print(int n) { if(n>9) { print(n/10); } printf("%d ", n%10); } int main() { int num = 1234; print(num); return 0; }
8.2.2 练习 2 :编写函数不允许创建临时变量,求字符串的长度。参考代码://第一种写法 #include <stdio.h> int Strlen(const char* str) { if(*str == '\0') return 0; else return 1+Strlen(str+1); } int main() { char *p = "abcdef"; int len = Strlen(p); printf("%d\n", len); return 0; }
//第二种写法 #include<stdio.h> int my_strlen(const char* s) { int count = 0; while (*s != '\0') { count++; s++; } return count; } int main() { char arr[] = "abcdef"; int len = my_strlen(arr); printf("%d\n", len); return 0; }
8.3 递归与迭代
8.3.1 练习 3 :求 n 的阶乘。(不考虑溢出)参考代码:int factorial(int n) { if(n <= 1) return 1; else return n * factorial(n-1); }
//n的阶乘1 #include<stdio.h> int main() { int n = 0; int i = 0; int ret = 1; scanf("%d", &n); //循环产生1~n-1的数 for (i = 1; i <= n; i++) { ret = ret * i; } printf("%d\n", ret); return 0; }
//n的阶乘2 #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); int ret = fac(n); printf("%d\n", ret); return 0; }
7.3.2 练习 4 :求第 n 个斐波那契数。(不考虑溢出)参考代码:#include<stdio.h> int count = 0;//全局变量 int fib(int n) { if (n <= 2) return 1; else return fib(n - 1) + fib(n - 2); } int main() { int n = 0; scanf("%d", &n); int ret = fib(n); printf("%d\n", ret); return 0; }
但是我们发现 有问题 ;在使用 fib 这个函数的时候如果我们要计算第 50 个斐波那契数字的时候特别耗费时间。使用 factorial 函数求 10000 的阶乘(不考虑结果的正确性),程序会崩溃。为什么呢?我们发现 fib 函数在调用的过程中很多计算其实在一直重复。如果我们把代码修改一下:#include<stdio.h> int count = 0;//全局变量 int fib(int n) { if (n == 3) count++; if (n <= 2) return 1; else return fib(n - 1) + fib(n - 2); } int main() { int n = 0; scanf("%d", &n); int ret = fib(n); printf("%d\n", ret); printf("%d\n", count); return 0; }
最后我们输出看看 count ,是一个很大很大的值。那我们如何改进呢?在调试 factorial 函数的时候,如果你的参数比较大,那就会报错: stack overflow (栈溢出)这样的信息。系统分配给程序的栈空间是有限的,但是如果出现了死循环,或者(死递归),这样有可能导致一直开辟栈空间,最终产生栈空间耗尽的情况,这样的现象我们称为栈溢出。那如何解决上述的问题:1. 将递归改写成非递归。2. 使用 static 对象替代 nonstatic 局部对象。 在递归函数设计中,可以使用 static 对象替代nonstatic 局部对象(即栈对象), 这不仅可以减少每次递归调用和返回时产生和释放 nonstatic 对象的开销,而且 static 对象还可以保存递归调用的中间状态,并且可为各个调用层所访问。比如,下面代码就采用了,非递归的方式来实现://求n的阶乘 int factorial(int n) { int result = 1; while (n > 1) { result *= n ; n -= 1; } return result; } //求第n个斐波那契数 int fib(int n) { int result; int pre_result; int next_older_result; result = pre_result = 1; while (n > 2) { n -= 1; next_older_result = pre_result; pre_result = result; result = pre_result + next_older_result; } return result; }
代码简化:#include<stdio.h> int fib(int n) { int a = 1; int b = 1; int c = 1; while (n > 2) { a = b; b = c; c = a + b; n--; } return c; } int main() { int n = 0; scanf("%d", &n); int ret = fib(n); printf("%d\n", ret); return 0; }
提示:1. 许多问题是以递归的形式进行解释的,这只是因为它比非递归的形式更为清晰。2. 但是这些问题的迭代实现往往比递归实现效率更高,虽然代码的可读性稍微差些。3. 当一个问题相当复杂,难以用迭代实现时,此时递归实现的简洁性便可以补偿它所带来的运行时开销。函数递归的几个经典题目(自主研究):1. 汉诺塔问题2. 青蛙跳台阶问题
本节就介绍到这里,下次再见。