如何在Java中返回x的符号?


Java中有多种方法可以返回一个数的符号,以下是其中的一些方法:

  • 使用Math.signum()方法

Math.signum()方法返回一个数的符号,如果该数为正数,则返回1.0,如果该数为负数,则返回-1.0,如果该数为0,则返回0.0。

例如:

double x = 10.5;
double sign = Math.signum(x);
System.out.println(sign); // 输出1.0
double x = -10.5;
double sign = Math.signum(x);
System.out.println(sign); // 输出-1.0
double x = 0;
double sign = Math.signum(x);
System.out.println(sign); // 输出0.0
  • 使用三元运算符

可以使用三元运算符来判断一个数的符号,如果该数大于0,则返回1,如果该数小于0,则返回-1,如果该数等于0,则返回0。

例如:

double x = 10.5;
int sign = x > 0 ? 1 : x < 0 ? -1 : 0;
System.out.println(sign); // 输出1
double x = -10.5;
int sign = x > 0 ? 1 : x < 0 ? -1 : 0;
System.out.println(sign); // 输出-1
double x = 0;
int sign = x > 0 ? 1 : x < 0 ? -1 : 0;
System.out.println(sign); // 输出0
  • 使用if语句

也可以使用if语句来判断一个数的符号,如果该数大于0,则返回1,如果该数小于0,则返回-1,如果该数等于0,则返回0。

例如:

double x = 10.5;
int sign;
if (x > 0) {
    sign = 1;
} else if (x < 0) {
    sign = -1;
} else {
    sign = 0;
}
System.out.println(sign); // 输出1
double x = -10.5;
int sign;
if (x > 0) {
    sign = 1;
} else if (x < 0) {
    sign = -1;
} else {
    sign = 0;
}
System.out.println(sign); // 输出-1
double x = 0;
int sign;
if (x > 0) {
    sign = 1;
} else if (x < 0) {
    sign = -1;
} else {
    sign = 0;
}
System.out.println(sign); // 输出0


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.