英文:
Java Math.signum doesn't evaluate workout error
问题
我想问一个关于 Java 中 Math.signum()
方法的问题。
我在 Java 新手系列教程的代码中编写了以下内容:
public class MathClass {
public static void main (String [] args) {
int a = 27;
int b = -32;
a = Math.abs(a) * Math.signum(b); // a 现在是 -27
System.out.println(a);
}
}
我认为,由于 Math.signum(b)
返回值为 -1.0F
的浮点数,这意味着 a
也会被转换为浮点数,然后 a
被赋值为 -27
。然而,当我运行这段代码时,出现了以下错误:
error: incompatible types: possible lossy conversion from float to int
a = Math.abs(a) * Math.signum(b); // a 现在是 -27
我对这个错误感到困惑。
我犯了什么错误?
英文:
I want to ask a question about Math.signum()
in Java.
I wrote the following code as part of the Java Dummies series tutorial:
public class MathClass {
public static void main (String [] args) {
int a = 27;
int b = -32;
a = Math.abs(a) * Math.signum(b); // a is now -27
System.out.println(a);
}
}
I thought that given that Math.signum(b)
returns a float of value -1.0F
, it would mean that a
would also be converted to a float, and a is assigned the value of -27
. However, when I run this code, I get the following error:
error: incompatible types: possible lossy conversion from float to int
a = Math.abs(a) * Math.signum(b); // a is now -27
I'm confused by the error.
What mistake am I making?
答案1
得分: 1
Math.signum(b)
返回一个浮点数,所以int * float的结果将是浮点类型,你试图将其存储为整型。如果你想要使用整型来保存结果,你需要将浮点数转换为整型。
a = (int)(Math.abs(a) * Math.signum(b));
否则,将结果存储在一个浮点数/双精度变量中:
float x = Math.abs(a) * Math.signum(b);
请注意,一旦变量被声明,你不能改变其类型!
英文:
Math.signum(b)
returns a float, so int * float will be of float type, which you are trying to store into an int. If you want to use an int for the result, you need to convert the float to an int.
a = Math.abs(a) * (int) Math.signum(b);
Otherwise, store the result in a float/double variable
float x = Math.abs(a) * Math.signum(b);
Note that once a variable is declared, you cannot change its type!
答案2
得分: 1
你的错误在于你调用了错误的 signum()
方法。
应该使用 Integer.signum(int i)
方法来代替 Math.signum(float f)
方法。
噢,还有,如果你打印 a
而不是 test
,代码实际上会编译并运行。
int a = 27;
int b = -32;
a = Math.abs(a) * Integer.signum(b);
System.out.println(a); // 输出:-27
英文:
Your mistake is that you're calling the wrong signum()
method.
Use the Integer.signum(int i)
method instead of the Math.signum(float f)
method.
Oh, and if you print a
instead of test
, the code will actually compile and run.
int a = 27;
int b = -32;
a = Math.abs(a) * Integer.signum(b);
System.out.println(a); // prints: -27
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论