+ 1
abs (x-y) how this function works in c++?
7 Respostas
+ 10
The abs function is defined in c++ under cstdlib with the following definition:
{ x, x>0;
abs(x) = | 0, x==0;
{ -x, x<0;
Thus, it is nothing but the modulus function in mathematics, ( f(x) = |x| ) and for negative values, abs is able to return a positive value :
Eg -
abs(10); //10
abs(-20); //20
Here is how you can define one yourself...
template<typename T>
T abs( T x)
{
if(x>=0) return x;
else return -x;
}
int x,y;
cin>>x>>y;
cout<<abs(x-y)<<abs(y-x)<<endl;
//Will print the same values...
Also, a similar function fabs for the same purpose exists in cmath header...
+ 10
given the following parameters:
x = 10
y = 5
5 -5
abs(x-y) == abs(y-x) == 5
+ 7
Great answer @Kinshuk.
+ 3
abs is absolute. So it takes the positive (absolute) value of whatever is in parenthesis.
+ 3
@Michael
Thank you! Just want to know if it helped @kalai or not...
+ 3
@kalai
Welcome ^_^
+ 1
yeah i got it thanks @kinshuk