JavaAlgorithms/Maths/AbsoluteValue.java

27 lines
565 B
Java
Raw Normal View History

package Maths;
2020-08-23 12:40:30 +08:00
import java.util.Random;
2019-08-15 09:12:33 +08:00
public class AbsoluteValue {
2020-10-24 18:23:28 +08:00
public static void main(String[] args) {
Random random = new Random();
2020-08-23 12:40:30 +08:00
2020-10-24 18:23:28 +08:00
/* test 1000 random numbers */
for (int i = 1; i <= 1000; ++i) {
int randomNumber = random.nextInt();
assert absVal(randomNumber) == Math.abs(randomNumber);
}
2020-10-24 18:23:28 +08:00
}
2020-10-24 18:23:28 +08:00
/**
* If value is less than zero, make value positive.
*
* @param value a number
* @return the absolute value of a number
*/
public static int absVal(int value) {
return value < 0 ? -value : value;
}
2019-08-15 09:12:33 +08:00
}