In this C++ tutorial, you will learn how to use copysign(x, y) function of cmath to get a new value with the magnitude of x and sign of y, with syntax and examples.

C++ copysign()

C++ copysign(x, y) returns a new value with the magnitude of x and sign of y.

Syntax

The syntax of C++ copysign() is

copysign(x, y)

where

ParameterDescription
xA double, float, long double, or integral type value.
yA double, float, long double, or integral type value.

Returns

The return value depends on the type of value passed for parameters x and y. The return value of copysign() is

  • double if x and y are double.
  • float if x and y are float.
  • long double if x and y are long double.
  • Promoted to the higher of the given arguments for integral type arguments.

The synopsis of copysign() function is

double copysign(double x, double y);
float copysign(float x, float y);
long double copysign(long double x, long double y);
Promoted copysign(Type1 x, Type2 y); // for integral type argument values

copysign() is a function of cmath library. Include cmath library at the start of program, if using copysign() function.

ADVERTISEMENT

Example

In this example, we read two values from user into x and y, and find the return value of copysign(x, y) function.

C++ Program

#include <iostream>
#include<cmath>
using namespace std;

int main() {
    double x, y, z;
    cout << "Enter x : ";
    cin >> x;
    cout << "Enter y : ";
    cin >> y;

    double result = copysign(x, y);
    cout << "copysign(x, y) : " << result << endl;
}

Output

Enter x : 5
Enter y : -2
copysign(x, y) : -5
Program ended with exit code: 0

x is positive and y is negative, hence result is negative.

Run#2

Enter x : -5
Enter y : -2
copysign(x, y) : -5
Program ended with exit code: 0

x is negative and y is negative, hence result is negative.

Run#3

Enter x : -5
Enter y : 2
copysign(x, y) : 5
Program ended with exit code: 0

x is negative and y is positive, hence result is positive.

Run#4

Enter x : 5
Enter y : 2
copysign(x, y) : 5
Program ended with exit code: 0

x is positive. and y is positive, hence result is positive.

Conclusion

In this C++ Tutorial, we learned the syntax of C++ copysign(), and how to use this function, with the help of examples.