📜  C++ copysign()(1)

📅  最后修改于: 2023-12-03 14:59:44.719000             🧑  作者: Mango

C++ copysign()

The copysign() function in C++ returns a value with magnitude of x and the sign of y. This means that the function basically returns the absolute value of x with the sign of y. It is a part of the <cmath> header file.

The syntax for the function is:

double copysign( double x, double y );

where x is the value whose magnitude is to be preserved and y is the value whose sign is to be used.

Parameters

The copysign() function takes two arguments - x and y. Both x and y should be of double data type.

Return Value

The copysign() function returns a double value with magnitude of x and the sign of y.

Example

Let us take the example of finding the absolute value of a quantity while preserving the sign.

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
   double x = -10.5, y = 2.0;

   double result = copysign( abs(x), y );
   // find the absolute value of x (-10.5) and preserve the sign of y (2.0)

   cout << "The result is: " << result << endl;

   return 0; 
}

Output:

The result is: -10.5

In this example, we have used the copysign() function to find the absolute value of x (-10.5) while preserving the sign of y (2.0). The output shows that the resulting value is -10.5.

Conclusion

The copysign() function in C++ is a very useful function that can be used to find the magnitude of a quantity while preserving its sign. This function is often used in mathematical applications that require manipulation of signed quantities.