How to use copysign() in C++
The copysign function takes in two arguments and returns a value with the magnitude of the first argument and the sign of the second argument.
To use the copysign function, the cmath header file needs to be included in the program:
#include <cmath>
Parameters
The function takes in two parameters:
- The first parameter determines the magnitude of the return value.
- The second parameter determines the sign of the return value.
Return value
The copysign function can have the return value of three types:
- float
- double
- long double
These types depend on the types of arguments the programmer gives to the functions.
If any argument passed to the
copysignfunction islong double, the return type islong double. If not, the return type isdouble. If both the arguments are of typefloat, the return type is alsofloat.
Example
- The code below shows the execution of a
copysignfunction when both the arguments are of the same type. The value returned in line 11 is also `double, which is the same as its arguments.
#include <iostream>#include <cmath>#include <typeinfo>using namespace std;int main() {//both the arguments are of type doubledouble x = 22;double y = - 3;// prints the return value to the standard outputcout << "The returned value is " << copysign(x, y) << endl;// the type of returned value is output d which means the returned value is of type double.cout << "The type of returned value is " << typeid(copysign(x, y)).name() << endl;return 0;}
- The code below shows the
copysignfunction when the arguments are of different types:
#include <iostream>#include <cmath>#include <typeinfo>using namespace std;int main(){ // first argument of type intint x = 34;//second argument of type doubledouble y = -54.3;// prints the return value to the standard outputcout << "The returned value is " << copysign(x, y) << endl;// the type of returned value is output d which means returned value is of type double.cout << "The type of returned value is " << typeid(copysign(x, y)).name() << endl;return 0;}
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved