我知道得到一个int的倒数会是这样的:
int foo = 5;
float recip = 1/foo;
Run Code Online (Sandbox Code Playgroud)
但你怎么去获得一个浮点数的倒数呢?会不会这样?现在我让用户输入倒数,这不是最佳的.有任何想法吗?
编辑
为了澄清这里的一些伪代码:
float input = 0.25;
int recip = (get reciprocal here);
System.out.println(recip); //should return 4
Run Code Online (Sandbox Code Playgroud)
谢谢!
你会如何将浮点数转换为int?
这取决于你想要在小数部分发生什么.
如果你想砍掉它,你可以施放:
float floatValue = 2.7f;
int value = (int)floatValue;
System.out.println(value); // 2
Run Code Online (Sandbox Code Playgroud)
如果要对其进行舍入,请使用JDK库中的各种舍入方法,例如Math.round(float).
float floatValue = 2.7f;
int value = Math.round(floatValue);
System.out.println(value); // 3
Run Code Online (Sandbox Code Playgroud)
你的评论:
我正在寻找更多的方法来找到值的倒数,而不是舍入值.例如,如果我有0.25作为我的值,那么我想收到4作为我的输出,等等.
如果倒数是一个超过该值,则:
float input = 0.25f;
int recip = (int)(1.0f / input);
System.out.println(recip); // 4
Run Code Online (Sandbox Code Playgroud)
...切断任何小数部分,或
float input = 0.25f;
int recip = Math.round(1.0f / input);
System.out.println(recip); // 4
Run Code Online (Sandbox Code Playgroud)
......围绕它.(并且还有其他四舍五入的方法可以让你控制半场比赛,半场比赛,半场比赛,半场比赛,半场比赛,而不是正向无限,等等.
旁注:与使用float相比,几乎没有充分的理由使用double.请注意,十进制常量,例如2.0,doubles.如果你想要floats,最后放一个f:2.0f.但是再次:使用double.:-)