How to Get the First Argument with the Sign of the Second Argument in Java


In this example, we will use Math.copySign() to get the first argument with the sign of the second argument.

Source Code

package com.beginner.examples;

public class CopySignExample {

    public static void main(String[] args){
    	//return the first argument with the sign of the second argument.
    	double a = -10.8;
    	int d1 = 5;
    	double b = 0;
    	int d2 = 6;
    	double c = 2.01;
    	int d3 = 7;
    	System.out.println("copySign of " + a + " in the direction of " + d1 + " is: " + Math.copySign(a, d1));
        System.out.println("copySign of " + b + " in the direction of " + d2 + " is: " + Math.copySign(b, d2));
        System.out.println("copySign of " + c + " in the direction of " + d3 + " is: " + Math.copySign(c, d3));
    }
}

Output:

copySign of -10.8 in the direction of 5 is: 10.8
copySign of 0.0 in the direction of 6 is: 0.0
copySign of 2.01 in the direction of 7 is: 2.01
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments