C++ copysign()

Last Updated On Monday 18th Apr 2022

copysign

The C++ copysign() function returns a value with the magnitude of first argument and sign of second argument. It takes the two arguments. It is also defined in the <cmath> header file.

Syntax

	copysign(x, y);
	

Parameters

The copysign() function takes two arguments which,

  • x– Value with the magnitude of the resulting value.
  • y – Value with the sign of the resulting value.

Return value

Returns value with the magnitude of x and the sign of y.

copy sign

copysign() prototype

	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
	

Example 1 : C++ copysign()

	#include <stdio.h>
#include <math.h>
int main () {
  printf ("copysign ( 10.0,-1.0) = %f\n", copysign( 10.0,-1.0));
  printf ("copysign (-10.0,-1.0) = %f\n", copysign(-10.0,-1.0));
  return 0;
}
	

Output

	copysign ( 10.0,-1.0) = -10.000000
copysign (-10.0,-1.0) = -10.000000
	

std copysign

Example 2 : C++ copysign() with arguments of same type

	#include <iostream>
#include <cmath>
using namespace std;

int main() {
    double x = 13.15, y = -23.0, result;
    result = copysign(x, y);
    cout << "copysign(" << x << "," << y << ") = " << result << endl;
    return 0;
}
	

Output

	copysign(13.15,-23) = -13.15
	

Example 3 : C++ copysign() with arguments of different type

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

Output

	copysign(14.15,-24) = -14.15