常用math函数
1 #include <stdio.h> 2 #include <math.h> 3 4 /*绝对值*/ 5 int main(){ 6 double db=-12.56; 7 printf("%.2f ",fabs(db)); 8 return 0; 9 }
1 #include <stdio.h> 2 #include <math.h> 3 4 /*向下(floor)向上(ceil)取整*/ 5 int main(){ 6 double db1=-5.2,db2=5.2; 7 printf("%.0f %.0f ",floor(db1),ceil(db1)); 8 printf("%.0f %.0f ",floor(db2),ceil(db2)); 9 return 0; 10 }
1 #include <stdio.h> 2 #include <math.h> 3 4 /*2的三次方*/ 5 int main(){ 6 double db =pow(2.0,3.0); 7 printf("%f ",db); 8 return 0; 9 }
1 #include <stdio.h> 2 #include <math.h> 3 4 /*算术平方根*/ 5 int main(){ 6 double db=sqrt(2.0); 7 printf("%f ",db); 8 return 0; 9 }
#include <stdio.h> #include <math.h> /*返回double类型以自然数为底的对数*/ int main(){ double db=log(1.0); printf("%f ",db); return 0; }
注:C中没有对任意底求对数的函数,用换底公式logzb=logeb/logez
1 #include <stdio.h> 2 #include <math.h> 3 4 /*弧度制*/ 5 /*acos是一个函数,其功能是求反余弦。acos(-1.0)就是求-1.0的反余弦,再赋值给double类型的常变量pi*/ 6 const double pi=acos(-1.0); 7 8 int main(){ 9 /* PI*一次旋转的角度数/180 */ 10 double db1=sin(pi*45/180); 11 double db2=cos(pi*45/180); 12 double db3=tan(pi*45/180); 13 printf("%f,%f,%f ",db1,db2,db3); 14 return 0; 15 }
1 #include <stdio.h> 2 #include <math.h> 3 4 /*反三角函数*/ 5 int main(){ 6 double db1=asin(1); 7 double db2=acos(-1.0); 8 double db3=atan(0); 9 printf("%f,%f,%f ",db1,db2,db3); 10 return 0; 11 }
1 #include <stdio.h> 2 #include <math.h> 3 4 int main(){ 5 double db1=round(3.40); 6 double db2=round(3.45); 7 double db3=round(3.50); 8 double db4=round(3.55); 9 double db5=round(3.60); 10 printf("%d, %d, %d, %d ,%d ",(int)db1,(int)db2,(int)db3,(int)db4,(int)db5); 11 return 0; 12 }