文章目录
一、绝对值
1.abs和fabs的区别
函数 | C库 | C++库 | 作用 | 原型 |
---|---|---|---|---|
abs(x) | <stdlib.h> | <cstdlib> | 求整型数的绝对值 | ![]() |
fabs(x) | <math.h> | <cmath> | 求浮点数的绝对值 | ![]() |
2.整数abs(x)
//C语言
#include<stdio.h>
#include<stdlib.h>
int main(void) {
// your code goes here
int a = 10;
long b = 100;
long long c = 1000;
printf("%d\n", abs(a));
//10
printf("%ld\n", abs(b));
//10
printf("%lld\n", abs(c));
//10
return 0;
}
//C++
#include <iostream>
#include <cstdio>
using namespace std;
int main(void) {
// your code goes here
int a=10;
long b=100;
long long c=1000;
cout<<abs(a)<<endl;
//10
cout<<abs(b)<<endl;
//100
cout<<abs(c)<<endl;
//1000
return 0;
}
3.fabs(x)
//C语言
#include <stdio.h>
#include <math.h>
int main(void) {
// your code goes here
float a = -3.14;
double b = -3.141;
printf("%f\n", fabs(a));
//-3.140000
printf("%lf\n", fabs(b));
//-3.141000
return 0;
}
//C++
#include <iostream>
#include <cmath>
using namespace std;
int main(void) {
// your code goes here
float a=-4.13556;
double b=-3.14;
cout<<fabs(a)<<endl;
//4.13556
cout<<fabs(b)<<endl;
//3.14
return 0;
}
4.绝对值陷阱
C/C++之最值limits.h(climits)和limits头文件
二、n次方
1.头文件
#include <math.h> //#include <cmath>
2.原型
double pow(double __x, double __y)
3.例如
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
cout << pow(2, 3) << endl;
//8
cout << pow(2.5, 2) << endl;
//6.25
cout << pow(4, 0.5) << endl;
//2
return 0;
}
三、平方根
1.头文件
#include <math.h> //#include <cmath>
2.原型
double sqrt(double __x)
3.例如
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
cout << sqrt(4) << endl;
//2
cout << sqrt(6.25) << endl;
//2.5
return 0;
}