Home » C++ programming language

abs() function with example in C++

C++ abs() function: Here, we are going to learn about the abs() function with example of cmath header in C++ programming language.
Submitted by IncludeHelp, on April 26, 2019

C++ abs() function

abs() function is a library function of cmath header, it is used to find the absolute value of the given number, it accepts a number and returns absolute value.

Note: abs() function is also declared in <stdlib.h> header file but it is compatible for integer values, in C++ 11, the enhanced version of abs() function is declared in math header and it casts the given value in double and returns the absolute value, it is compatible with double values too.

Syntax of abs() function:

    abs(x);

Parameter(s): x – is the number whose absolute value is returned.

Return value: double – it returns double value that is the absolute value of x.

Example:

    Input:
    float x = -1012.232;

    Function call:
    abs(x);

    Output:
    1012.232

C++ code to demonstrate the example of abs() function

// C++ code to demonstrate the example of 
// abs() function
#include <iostream>
#include <cmath>
using namespace std;

// main() section
int main()
{
    float x;
    float result;
    
    x = -10;
    cout<<"abs("<<x<<"): "<<abs(x)<<endl;

    x = -1012.232;
    cout<<"abs("<<x<<"): "<<abs(x)<<endl;    

    x = 1012.232;
    cout<<"abs("<<x<<"): "<<abs(x)<<endl;    

    x = -.908;
    cout<<"abs("<<x<<"): "<<abs(x)<<endl;    
    
    return 0;
}

Output

abs(-10): 10 
abs(-1012.23): 1012.23 
abs(1012.23): 1012.23
abs(-0.908): 0.908
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.