C++中的绝对值函数

C++中有两个库函数下有对应的求绝对值的函数:

  1. #include<stdlib.h>内,有abs()函数,可以对整型变量求绝对值。示例如下:
    #include<iostream>
    #include<stdlib.h>
    using namespace std;
    int main()
    {
        int a=-1;
        cout<<abs(a);
        return 0;
    }

    输出即为a的绝对值1。

  2. #include<math.h>内,有fabs()函数,可以对浮点型变量求绝对值。示例如下:
    #include<iostream>
    #include<math.h>
    using namespace std;
    int main()
    {
        int a=-1;
        cout<<fabs(a);
        return 0;
    }