函数案例:用初中数学,写一个数学方程f(x) = 2*x+1;
#include <stdio.h>
int f(int x) //定义一个f(x)函数;
{
return 2*x + 1; //即return f(x)的值;
}
int main()
{
int x;
printf("有函数f(x)=2*x+1(x为整数),请输入x的值:");
scanf("%d",&x);
printf("f(%d)=%d",x,f(x));
return 0;
}
函数的声明
c语言自定义函数可以不定义直接申明吗?
只要保证所有调用该函数的语句,都在同一个源文件中,并且都在该函数定义代码之后,可以不加单独的声明。
栗子见下文两种不同的方法
函数的递归求当n=100,时1+2+3…+n的总和;
#include <stdio.h> //导如输入输出头文件
int sum(int n);//声明函数
int main(){
//主函数
int a=sum(100);
printf("%d",a);
return 0;
}
int sum(int n){
//求和函数实现
//如果n为1,无需求和,直接返回1
if(n==1){
return 1;
}
//如果n大于1,就返回n加上1+2+3.....+n-1的和
return n+sum(n-1);
}
变量的访问有两种方式:
- 通过变量名;
- 通过地址;就是指针;
心法如下,熟读并背诵;
- int x;变量x;
- int *p;指针变量p;
- p = &x;将x的地址赋值给变量p,称为p是指向x的指针;就是p是x的地址;
- 地址运算符&: 只能用于内存中的对象,即变量与数组元素; 不能用于表达式、常量、register类型的变量(关键字型的变量);
- *p = x; 即 *(&x) = x;
指针案例:用函数变换a的值;
#include <stdio.h>
void modify(int *pa) //形参是一个地址,即&a;
{
*pa = 200; //将200赋值给*(&a)的变量;*(&a)就是a,即变量a由100变成200;
}
int main()
{
int a = 100;
modify(&a); //因为变量a的作用域不在函数modify中,只能用通过地址的方式访问变量;
printf("原来a=100,现在a=%d",a); //通过变量名a访问变量为200;
return 0;
}
结构体指针案例:用函数变换a的值;
课本见推荐网站 PS:使用语言,首先要掌握它的说明书。
https://www.runoob.com/cprogramming/c-structures.html
一个习惯:定义结构体时,结构体标签的首字母习惯大写,为了区别于变量名;栗子:struct Data{};
#include <stdio.h>
#include <stdlib.h> //malloc,NULL
#include <string.h> //strcpy
struct Words //结构体Words的定义,首字母习惯大写;
{
char title[50]; //就定义一个数据;
};
char *strC = "C语言是世界上最好的语言";
char *strJAVA = "JAVA语言是世界上最好的语言";
char *strpython = "C++语言是世界上最好的语言";
/*置换函数的前置声明*/
void modify(struct Words* word);
struct Words* p(char *str);
int main( )
{
struct Words word;
strcpy( word.title, strC);
printf( "title1 : %s\n", word.title);
modify(&word);
printf( "title2 : %s\n", word.title);
struct Words* pWord = p(strpython);
printf( "title3 : %s\n", pWord->title);
return 0;
}
void modify( struct Words* word)
{
strcpy(word->title, strJAVA); //疑问:怎样使用字符串的指针输入?2020.11.7
}
struct Words* p(char *str)
{
struct Words* newWord = (struct Words*)malloc(sizeof(struct Words));
strcpy( newWord->title, str);
return newWord;
}
链表
是用指针把堆区的多块内存连接起来的结构就是链表
链表:
节点:每一块内存
数据:每一个节点里面存放