基础补充:
- 代码规范
定义变量名的时候尽量规范,养成习惯,
下面一些是常用的变量名字 、之后继续补充(拒绝再用abcd定义)
英文单词缩写:
temporary -- temp 暂时、临时的 -- tmp
flag 标志、标识 -- flg
count 计数
increment 加1 --inc
decrement 减1 -- dec
message 消息 -- msg
value 值 -- val
加 -- addition -- add
减 -- subtraction -- sub
乘 -- multiplication -- mul
除 -- divide -- div
取余数 -- modulus -- mod
max -- 最大值
min -- 最小值
定义函数名的时候注意,有多个单词时,用下划线连接;举个栗子
(1)、列出所有质数(prime)
void list_all_prime()或写成void list_primes()
{
}
(2)、查找出最大值的位置(position)
int fine_max_pos(int arr[], int n)
{
}
注释
(1)、// /* */
#include <stdio.h>
int main(void)
{
printf("你好,世界\n"); //打印...
return 0;
}
(2)、函数注释时的规范写法
/**
*在数组中查找出最大值的位置。
*@param arr 一个数组
*@param n 数组的长度
*@return 最大值的下标
*/
int fine_max_pos(int arr[], int n)
{
}
2. 基本类型
3. 运算符
4. 控制流
函数
函数的使用可以省去重复代码的编写,降低代码重复率
##1、看代码的时候经常能看到main函数中有这两变量,那它们到底是什么呢?
首先argc
#include "stdio.h"
int main(int argc, char** argv)
{
//我们打印出来看看
printf("argc = %d\n", argc);
return 0;
}
运行结果:
zjs@ubuntu:~/test$ ./test
argc = 1
zjs@ubuntu:~/test$ ./test fasfa
argc = 2
zjs@ubuntu:~/test$ ./test fasfa fasfa
argc = 3
可见这个变量等同于我们在命令行中打印的东西
然后argv
//解释下着c v 的意思
// c = count 数数的意思,它是一个整数
// v = vector 向量的意思,打印出来的字符串是保存在这个argv里面的,然后我们将它显示出来看看效果
#include "stdio.h"
int main(int argc, char **argv)
{
int i;
printf("argc = %d\n", argc);
for (i = 0;i < argc; i++)
{
printf("%s\n",argv[i]);
}
return 0;
}
运行结果:
zjs@ubuntu:~/test$ ./test
argc = 1
./test
zjs@ubuntu:~/test$ ./test 1 2 3 4 5
argc = 6
./test
1
2
3
4
5
再来认识一个C语言中的函数atoi,它是在<stdlib.h> 头文件中的;
//解释下着c v 的意思
// c = count 计数的意思,它是一个整数
// v = vector 向量的意思,打印出来的字符串是保存在这个argv里面的,我们把打印出来的字符串加起来(求和);
//atoi:
//a -- argument value(参数值)
//i -- int (整数)
#include "stdio.h"
#include "stdlib.h"
int main(int argc, char **argv)
{
int i;
int s = 0;
printf("argc = %d\n", argc);
for (i = 0;i < argc; i++)
{
int num = atoi(argv[i]);
s = s = num;
}
printf("s = %d\n",s);
return 0;
}
运行结果:
zjs@ubuntu:~/test$ gcc test.c -o test
zjs@ubuntu:~/test$ ./test
s = 0
zjs@ubuntu:~/test$ ./test 1 2 3 4 5
s = 15
以上几个展示就是对main函数经常看到的阐述的理解,还是有点不足
##2、函数的调用
当调用函数时,需要关心5要素:
1、头文件:包含指定的头文件
2、函数名字:函数名字必须和头文件声明的名字一样
3、功能:需要知道此函数能干嘛后才调用
4、参数:参数类型要匹配
5、返回值:根据需要接收返回值
#include <time.h>
time_t time(time_t *t);
功能:获取当前系统时间
参数:常设置为NULL
返回值:当前系统时间, time_t 相当于long类型,单位为毫秒
#include <stdlib.h>
void srand(unsigned int seed);
功能:用来设置rand()产生随机数时的随机种子
参数:如果每次seed相等,rand()产生随机数相等
返回值:无
#include <stdlib.h>
int rand(void);
功能:返回一个随机数值
参数:无
返回值:随机数
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
time_t tm = time(NULL);//得到系统时间
srand((unsigned int)tm);//随机种子只需要设置一次即可
int r = rand();
printf("r = %d\n", r);
return 0;
}
待续未完