×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

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

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.

Sample Input and Output

Input:
float x = -1012.232;

Function call:
abs(x);

Output:
1012.232

Example

// 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


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.