English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Usage and example of copysign() function

C++ Library Function <cmath>

C ++accepts two parameters and returns a value that has the size of the first parameter and the sign of the second parameter.

The function in<cmath>Defined in the header file.

copysign() prototype[From C ++ 11Standard begins]

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); // Additional overloads for arithmetic types

From C ++ 11Starting from C, if the parameters passed to copysign() are of type long double, the returned type Promoted is long double. If not, the returned type Promoted is double.

copysign() parameters

  • x:Value with the size of the result value.

  • y:Value with the sign of the result value.

copysign() return value

The copysign() function returns a value that assigns the sign of the parameter y to x.

Example1:The copysign() function for parameters of the same type

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    double x = 34.15, y = -13.0, result;
    
    result = copysign(x, y);
    cout << "copysign(" << x << "," << y << ") = " << result << endl;
    
    return 0;
}

When the program is run, the output is:

copysign(34.15,-13) = -34.15

Example2:The copysign() function for different types of parameters

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    double x = 34.15, result;
    int y = -54;
    result = copysign(x, y);
    cout << "copysign(" << x << "," << y << ") = " << result << endl;
    return 0;
}

When the program is run, the output is:

copysign(34.15,-54) = -34.15

C++ Library Function <cmath>