C++ Math copysign
The function outputs a result that retains the absolute value of x and the sign of y.
Syntax
Consider two variables 'x' and 'y'. The syntax is as follows:
float copysign(float x, float y);
double copysign(double x, double y);
long double copysign(long double x, long double y);
promoted copysign(type1 x, type2 y);
Note: If any argument is of long double type, then the return type is promoted to long double. If not, the return type is promoted to double.
Parameter
x : Value with the magnitude.
y : Value with the sign.
Return value
It provides the result by considering the absolute value of x and the sign of y.
Example 1
Let's examine a straightforward scenario where the y variable holds a positive value.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
double x=15.9;
double y=9;
std::cout << "Values of x and y are: " <<x<<", "<<y<< std::endl;
cout<<"copysign(15.9,9) ="<<copysign(x,y);
return 0;
}
Output:
Values of x and y are: 15.9, 9
copysign(15.9,9) =15.9
In this instance, the copysign function retrieves the absolute value of x, which is 15.9, while inheriting the sign of y, which is negative.
Example 2
Let's explore a basic scenario where the value of y is less than zero.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
double x=-8.6;
double y=-3.2;
std::cout << "Values of x and y are :" <<x<<" ,"<<y<< std::endl;
cout<<"copysign(-8.6,-3.2) ="<<copysign(x,y);
return 0;
}
Output:
Values of x and y are :-8.6 ,-3.2
copysign(-8.6,-3.2) =-8.6
In this instance, the copysign function yields the absolute value of x, which is 8.6, maintaining the sign of y, which is negative.