一、typedef
typedef是一个很有用的东西,它能够给复杂的数据类型起一个别名,这样在使用中就可以用别名来代替原来的写法。例如,当数据类型是 long long 时,就可以像下面的例子这样用LL来代替 long long,以避免因在程序中出现大量的 long long 而降低编码效率。
#include <cstdio>
typedef long long LL; //给long long起一个别名LL
int main() {
LL a = 123456789012345LL, b = 234567890123456LL; //直接使用LL
printf("%lld\n",a+b);
return 0;
}
输出结果:
358024679135801
二、常用math函数
1. fabs(double x)
该函数用于对double型变量取绝对值,示例如下:
#include <stdio.h>
#include <math.h>
int main() {
double db = -12.56;
printf("%.2f\n",fabs(db));
return 0;
}
输出结果:
12.56
2. floor(double x)和ceil(double x)
这两个函数分别用于double型变量的向下取整和向上取整,返回类型为double型,示例如下:
#include <stdio.h>
#include <math.h>
int main() {
double db1 = -5.2, db2 = 5.2;
printf("%.0f %.0f\n",floor(db1),ceil(db1));
printf("%.0f %.0f\n",floor(db2),ceil(db2));
return 0;
}
输出结果:
-6 -5
5 6
3. sqrt(double x)
该函数用于返回double 型变量的算术平方根,示例如下:
#include <stdio.h>
#include <math.h>
int main() {
double db = sqrt(2.0);
printf("%f\n",db);
return 0;
}
输出结果:
1.414214
4. pow(double r, double p)
该函数用于返回rp,要求 r 和 p 都是 double 型,示例如下:
#include <stdio.h>
#include <math.h>
int main() {
double db = pow(2.0, 3.0);
printf("%f\n",db);
return 0;
}
输出结果:
8.000000
5. log(double x)
该函数用于返回 double 型变量的以自然对数为底的对数,示例如下:
扫描二维码关注公众号,回复:
3590089 查看本文章
#include <stdio.h>
#include <math.h>
int main() {
double db = log(1.0);
printf("%f\n",db);
return 0;
}
输出结果:
0.000000
C语言中没有对任意底数求对数的函数,因此必须使用换底公式来将不是以自然对数为底的对数转换为以e为底的对数,即 logab = logeb/logea
6. sin(double x)、cos(double x) 和 tan(double x)
这三个函数分别返回 double 型变量的正弦值、余弦值和正切值,参数要求是弧度制,示例如下:
#include <stdio.h>
#include <math.h>
const double pi = acos(-1.0);
int main() {
double db1 = sin(pi * 45 / 180);
double db2 = cos(pi * 45 / 180);
double db3 = tan(pi * 45 / 180);
printf("%f, %f, %f\n", db1, db2, db3);
return 0;
}
计算结果:
0.707101, 0.707107, 1.000000
此处把 pi 定义为精确值 acos(-1.0)(因为 cos(pi) = -1)。
7. asin(double x)、acos(double x) 和 atan(double x)
这三个函数分别返回 double 型变量的反正弦值、反余弦值和反正切值,示例如下:
#include <stdio.h>
#include <math.h>
int main() {
double db1 = asin(1);
double db2 = acos(-1.0);
double db3 = atan(0);
printf("%f, %f, %f\n", db1, db2, db3);
return 0;
}
计算结果:
1.570796, 3.141593, 0.000000
8. round(double x)
该函数用于将 double 型变量 x 四舍五入,返回类型也是 double 型,需进行取整,示例如下:
#include <stdio.h>
#include <math.h>
int main() {
double db1 = round(3.40);
double db2 = round(3.45);
double db3 = round(3.50);
double db4 = round(3.55);
double db5 = round(3.60);
printf("%d, %d, %d, %d, %d\n", (int)db1, (int)db2,(int)db3, (int)db4, (int)db5);
return 0;
}
计算结果:
3, 3, 4, 4, 4
练习题
求一元二次方程ax2+bx+c=0的根,三个系数a, b, c由键盘输入,且a不能为0,且保证b2-4ac>0。 程序中所涉及的变量均为double类型。
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c, d;
double r1, r2;
scanf("%lf %lf %lf",&a,&b,&c);
d = b*b - 4*a*c;
if(a!=0) {
if(d>0) {
r1 = (-b+sqrt(d))/(2*a);
r2 = (-b-sqrt(d))/(2*a);
printf("r1=%7.2f\nr2=%7.2f", r1, r2);
}
}
return 0;
}
计算结果:
输入
1 3 2
输出
r1= -1.00
r2= -2.00