Copysign() function in C++


Given the task is to show the working of copysign() in C++.

The copysign() function is a part of the C++ standard template library. It takes two arguments and produces the result by combining the magnitude of the first value and the sign of the second value.

<math.h> or <cmath> header file should be included to call this function.

Syntax

The syntax is as follows −

copysign(x,y)

Example

Input: copysign(4,-5)
Output: -4

Explanation − The following example demonstrates how we can copy the sign of one value to the magnitude of another value. The sign of the second argument, that is “-“and the magnitude of the first argument that is 4 combined produce the result -4.

Example

Input: copysign(-1.3,4.4)
Output: 1.3

Explanation − The sign of the second argument, that is “+” and the magnitude of the first argument that is 1.3 combined produce the result 1.3. This example also shows that whole number values as well as decimal values can also be passed as an argument in the copysign() function.

Approach used in the below program as follows −

  • Choose two values, one whose magnitude has to be considered and the other one whose sign has to be considered, let’s say -1.1 and 2.3.
  • Now pass the two values into the copysign() function as the arguments.
  • The first argument should be the value whose magnitude has to be considered and the second argument should be the value whose sign has to be taken.

Example

 Live Demo

#include <iostream>
#include<cmath>
using namespace std;
int main() {
   cout<<copysign(-1.1,2.3);
   return 0;
}

Output

If we run the above code it will generate the following output −

1.1

// The sign of the second argument, that is “+” and the magnitude of the first argument that is 1.1 combined produce the result 1.1.

Updated on: 20-Jan-2020

57 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements