常用函数库



常用math函数

#include <math.h>
fabs(double x) return double;取绝对值;
floor(double x) return double;向下取整;
ceil(double x) return double;向上取整;
pow(double r, double p) return double; 求幂;r的p次方
sqrt(double x) return double; 根号;
log(double x) return double;
sin(double x) cos(double x) tan(double x) return double;
asin(double x) acos(double x) atan(double x) return double;
round(double x) return double; 对x进行四舍五入;

switch的用法

switch(x)
{
    
    
	case 1: 
		...
		break;
	case 2:
		...
		break;
	default:
		...
}

memset和fill、以及string.h函数、algorithm函数

#include <string.h>
memset(arr, 0, sizeof(arr));
strlen(s); //字符串s
strcmp(a, b); //字符串a,b,
//if(a==b) return 0;
//if(a>b) return 正整数;
//if(a<b) return 负整数;
strcpy(a, b); //b复制给a;
strcat(a,b) //a后接b;
#include <stdio.h>
scanf("%d", &n); == scanf(screen, "%d", &n); //screen表示屏幕;
printf("%d", n); == printf(screen, "%d", n); //screen表示屏幕;
sscanf() == string + scanf;
sprintf() == string + printf;
sscanf(str, "%d", &n); //把字符串str中的内容以"%d"的格式写到n中(从左到右);
sprintf(str, "%d", n); //把n以%d的格式写到字符串str中(从左到右)

memset只能用来赋值0或-1;因为memset是按字节赋值;
赋值其他的数值使用fill函数,

#include <algorithm>
fill(arr, arr+n, 233)

以数组作为函数参数

数组作为参数时,参数中的数组第一维不需要填写长度(如果是二维数组,那么第二维需要填写长度),实际调用时也只需要填写数组名。
数组作为参数时,在函数中对数组元素的修改就等同于是对原数组元素的修改(这与普通的局部变量是不一样的)

void test(int a[], int b[][5])
{
    
    
	...
}

结构体的构造函数

所谓构造函数是用来初始化结构体的一种函数,直接定义在结构体中;
构造函数的特点:它不需要写返回类型,且函数名与结构体名相同。
对于一个普通定义的结构体,其内部会生成一个默认的构造函数(但不可见)。"studentInfo(){}"就是默认生成的构造函数,可以看到这个构造函数的函数名和结构体类型名相同,它没有返回类型

struct stuentInfo
{
    
    
	int id;
	char gender;
	studentInfo(){
    
    }
};

struct stuentInfo
{
    
    
	int id;
	char gender;
	studentInfo(int _id, char _gender):id(_id), gender(_gender){
    
    }
};
studentInfostu = studentInfo(10086, 'M');
char str[100];
cin.getline(str, 100); //输入一行;
string str;
getline(cin, str);

浮点数的比较

const double eps = 1e-8;
#define Equ(a, b) (fabs((a)-(b))) < (eps) //==等于
#define More(a, b) (((a)-(b)) > (eps)) //>大于
#define Less(a, b)  (((a)-(b)) < (-eps)) //<小于
#define MoreEqu(a, b) (((a)-(b)) > (-eps)) //>=大于等于
#define LessEqu(a, b) (((a)-(b)) < (eps)) //<=小于等于
const double Pi = acos(-1.0)

对一般的OJ系统来说,一秒能承受的运算次数大约是10^7 ~ 10^8,

while(scanf("%d", &n) != EOF)
{
    
    
	...
}

快速求幂

typedef long long LL;
LL pow(LL a, LL b, LL m) // 求 a^b % m;
{
    
    
    LL ans = 1;
	while(b > 0)
	{
    
    
		if(b % 2 == 1)
		{
    
    
			ans = ans * a % m;
		}
        a = a * a % m;
		b = b / 2;
	}
	return ans;
}

最大公约数

int  gcd(int a, int b)
{
    
    
	if(b==0) return a;
	else return gcd(b, a % b);
}

猜你喜欢

转载自blog.csdn.net/weixin_42137874/article/details/113607760