C MathCopySign Examples

In this tutorial, we will learn about the C# Math.CopySign() method, and learn how to use this method to get a value formed using magnitude of one number and the sign of other number, with the help of examples.

CopySignDouble x, Double y

Math.CopySign(x, y) returns a value with the magnitude of x and the sign of y.

Syntax

The syntax of CopySign() method is

Math.CopySign(Double x, Double y)

where

Parameter Description
x The Double value whose magnitude is used in the result.
y The Double value whose sign is the used in the result.

Return Value

The method returns Double value.

Example 1 CopySignDouble, Double

In this example, we will use Math.CopySign() method and get a number whose magnitude is from the first argument and the sign is from second argument.

C# Program

using System;
 
class Example {
    static void Main(string[] args) {
        Double x, y, result;

        x = 2;
        y = -8;
        result = Math.CopySign(x, y);
        Console.WriteLine($"CopySign({x}, {y}) = {result}");

        x = 2;
        y = 8;
        result = Math.CopySign(x, y);
        Console.WriteLine($"CopySign({x}, {y}) = {result}");

        x = -2;
        y = 8;
        result = Math.CopySign(x, y);
        Console.WriteLine($"CopySign({x}, {y}) = {result}");
    }
}

Output

CopySign(2, -8) = -2
CopySign(2, 8) = 2
CopySign(-2, 8) = 2

For CopySign(2, -8), magnitude is copied from 2 and sign is copied from -8, hence the result -2.

For CopySign(2, 8), magnitude is copied from 2 and sign is copied from 8, hence the result 2.

For CopySign(-2, 8), magnitude is copied from -2 and sign is copied from 8, hence the result 2.

Conclusion

In this C# Tutorial, we have learnt the syntax of C# Math.CopySign() method, and also learnt how to use this method with the help of C# example programs.