Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++

How to use copysign() in C++

Sadia Zubair

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:

  1. The first parameter determines the magnitude of the return value.
  2. 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 copysign function is long double, the return type is long double. If not, the return type is double. If both the arguments are of type float, the return type is also float.

Example

  1. The code below shows the execution of a copysign function 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 double
  double x = 22;
  double y = - 3;
  // prints the return value to the standard output
  cout << "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;
}
  1. The code below shows the copysign function when the arguments are of different types:
#include <iostream>
#include <cmath>
#include <typeinfo> 
using namespace std;

int main()
{   // first argument of type int
    int x = 34;
    //second argument of type double
    double y = -54.3;
    // prints the return value to the standard output
    cout << "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;
}

RELATED TAGS

c++

CONTRIBUTOR

Sadia Zubair
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring