copysign() Function
The copysign()
function returns a value that retains the magnitude of one operand while adopting the sign of the other. This function is useful in numerical computations where you need to control the sign of a result without modifying its absolute value.
Syntax of copysign()
double copysign(double x, double y);
float copysignf(float x, float y);
long double copysignl(long double x, long double y);
Parameters
Parameter | Description |
---|---|
x | Value whose magnitude is used in the resulting value. |
y | Value whose sign is used in the resulting value. |
Return Value
The function returns a value that has the magnitude of x
and the sign of y
.
The copysign()
function is particularly useful when the sign of a numerical result needs to be explicitly controlled in computations without affecting the magnitude. This makes it ideal for applications involving complex numerical algorithms where sign manipulation is required.
Examples for copysign()
Example 1: Basic Usage to Assign a Negative Sign
This example demonstrates how copysign()
is used to assign a negative sign to a positive magnitude.
Program
#include <stdio.h>
#include <math.h>
int main() {
double magnitude = 5.0;
double signSource = -3.0;
double result = copysign(magnitude, signSource);
printf("Result: %f\n", result);
return 0;
}
Explanation:
- The variable
magnitude
is set to5.0
, which provides the magnitude for the result. - The variable
signSource
is set to-3.0
, providing the negative sign. - The function
copysign()
returns-5.0
, combining the magnitude of5.0
with the sign of-3.0
.
Program Output:
Result: -5.000000
Example 2: Applying copysign() on Floating-Point Values
This example illustrates the use of copysignf()
with float values to ensure the sign is transferred while the magnitude remains unchanged.
Program
#include <stdio.h>
#include <math.h>
int main() {
float a = 7.5f;
float b = -2.0f;
float result = copysignf(a, b);
printf("Result: %f\n", result);
return 0;
}
Explanation:
- The variable
a
is initialized with a positive float value of7.5f
. - The variable
b
is initialized with a negative float value of-2.0f
. - The function
copysignf()
returns-7.5f
, preserving the magnitude ofa
while adopting the sign ofb
.
Program Output:
Result: -7.500000
Example 3: Demonstrating copysignl() with Long Double Values
This example demonstrates the use of copysignl()
with long double values, showing how the function transfers the sign correctly while preserving the magnitude.
Program
#include <stdio.h>
#include <math.h>
int main() {
long double m = 12.34L;
long double s = -0.0L;
long double result = copysignl(m, s);
printf("Result: %Lf\n", result);
return 0;
}
Explanation:
- The variable
m
is assigned a long double value of12.34L
, which sets the magnitude. - The variable
s
is assigned-0.0L
to provide a negative sign. - The function
copysignl()
returns-12.34L
, merging the magnitude ofm
with the sign ofs
.
Program Output:
Result: -12.340000