+ 1

abs (x-y) how this function works in c++?

12th Jun 2017, 2:16 PM
kalai
7 Answers
+ 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...
12th Jun 2017, 4:33 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 10
given the following parameters: x = 10 y = 5 5 -5 abs(x-y) == abs(y-x) == 5
12th Jun 2017, 3:51 PM
Burey
Burey - avatar
+ 7
Great answer @Kinshuk.
12th Jun 2017, 4:58 PM
Michael Simnitt
Michael Simnitt - avatar
+ 3
abs is absolute. So it takes the positive (absolute) value of whatever is in parenthesis.
12th Jun 2017, 3:21 PM
Rrestoring faith
Rrestoring faith - avatar
+ 3
@Michael Thank you! Just want to know if it helped @kalai or not...
12th Jun 2017, 4:58 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 3
@kalai Welcome ^_^
13th Jun 2017, 1:33 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
yeah i got it thanks @kinshuk
13th Jun 2017, 12:22 PM
kalai