Appreciate if you can advise and share how to build Absolute function without using abs() or loop (if/else) , just work with operators (C )
CodePudding user response:
template<typename N>
N abs(const N& n)
{
const N arr[2] = {n, -n};
return arr[n < 0];
}
is one way. And it won't dump the pipeline either.
CodePudding user response:
I can offer the solution of your problem.
#include <iostream>
using namespace std;
int absolute(int number)
{
return number<0 ? -number : number;
}
int main()
{
int number;
cin>>number;
cout<<absolute(number);
return 0;
}
Input:
-4
Output:
4
Input:
4
Output:
4
CodePudding user response:
There is another way using a C 20 concept:
#include <iostream>
#include <concepts>
auto abs( std::integral auto num )
{
return num < 0 ? -num : num;
}
int main( )
{
std::cout << abs( -4 ) << ' ' << abs( 12345 ) << '\n';
}
