Math Copysign Function - C++ Programming Tutorial
C++ Course / Math Functions / Math Copysign Function

Math Copysign Function

BLUF: Mastering Math Copysign Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Math Copysign Function

C++ is renowned for its efficiency. Learn how Math Copysign Function enables low-level control and high-performance computing in the tutorial below.

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:

Example

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.

Example

#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:

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.

Example

#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:

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.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience