|
ไอที |
Java |
4740
รู้จักกับ method ที่ชื่อว่า signum ในภาษา Java เมธอดที่เอาไว้สำหรับเช็คค่าจำนวนลบ บวก หรือศูนย์
method ที่ชื่อว่า signum เป็น เมธอดที่เอาไว้สำหรับเช็คค่าว่าค่านั้นเป็นบวก เป็นลบ หรือเป็นศูนย์
BigInteger.signum() method returns -1, 0 or 1 as the value of this BigInteger is negative, zero or positive
method signum จะ return ค่าออกมาเป็น -1, 0 หรือ 1 ซึ่งค่าที่ได้ ถ้าเป็น 0 จะออกเป็น 0 ถ้าค่าเป็นจำนวนบวกจะได้ค่า 1 ส่วนถ้าเป็นจำนวนลบจะได้ -1
ตัวอย่างโค้ด
import java.math.BigInteger;
public class BigIntegerExam {
public static void main(String[] args) {
BigInteger bi1 = new BigInteger("0");
BigInteger bi2 = new BigInteger("10");
BigInteger bi3 = new BigInteger("-10");
// assign signum results of bi1, bi2, bi3 to i1, i2, i3
int i1 = bi1.signum();
int i2 = bi2.signum();
int i3 = bi3.signum();
// print i1, i2, i3 values
System.out.println(i1); // output 0
System.out.println(i2); // output 1
System.out.println(i3); // output -1
}
}
จากโค้ดด้านบน เรามี BigInteger 3 ตัวซึ่งมีค่า 0 10 -10 จากนั้นเราเอามาเรียก method ที่ชื่อว่า signum แล้วเก็บไว้ในตัวแปร int จากนั้นปริ้นออกมา ซึ่งจะได้ค่า 0 1 -1
BinInteger ที่มีค่า 0 เวลาเรียก method signum แล้วจะได้ค่า 0 เนื่องจากค่าเป็น 0
BinInteger ที่มีค่า 10 เวลาเรียก method signum แล้วจะได้ค่า 1 เนื่องจากค่าเป็น จำนวนบวก
BinInteger ที่มีค่า -10 เวลาเรียก method signum แล้วจะได้ค่า -1 เนื่องจากค่าเป็น จำนวนลบ
ที่มา http://www.functionexam.com/Java/java.math/BigInteger/signum().htm