简单方程未通过单元测试
我有一个接受 2 个整数作为参数并返回的方法:
public int method(int a, int b){
return Math.round((Math.abs(a-b)/3) - (Math.min(a,b)-1500)/10)
}
我创建了单元测试,它通过了值 1400 和 1500(预期值为 43),但是对于 1459 和 1500 失败了。预期输出是 18,但是我的方法返回17. 我相信这可能与舍入有关,但是我看不到任何明显的错误。将 17.7(6) 舍入到 18 应该不会有任何问题。
编辑:
实际函数略有不同(我没有 Math.abs(ab) 但我因此定义了“diff”变量。我可以向你们保证,我将其声明为 double diff; - 我不知道为什么它变成 int diff :) 已解决,谢谢 :)
I have method that takes 2 integers as arguments and returns:
public int method(int a, int b){
return Math.round((Math.abs(a-b)/3) - (Math.min(a,b)-1500)/10)
}
I have created unit test, which passes for values 1400 and 1500 (expected value is 43), however it fails for 1459 and 1500. The expected output is 18, however my method returns 17.
I believe this might have something to do with rounding, however i cannot see any obvious error. There should not be any problems with rounding 17.7(6) to 18.
EDIT:
the real function was slighty different (I did not have Math.abs(a-b) but instead I had defined "diff" variable as a result of this. I could promise you guys that i declared it as double diff; - I have no idea why it become int diff :) SOLVED thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当将
int
作为参数传递时,Math.abs
和Math.min
都返回int
,因此您的代码是进行整数除法而不是您期望的双除法。如果将3
和10
替换为3.0
和10.0
,您的代码应该按您的预期工作。Math.abs
andMath.min
both returnint
s when passedint
s as arguments, so your code is doing integer division instead of the double division that you are expecting. If you replace the3
and the10
with3.0
and10.0
, your code should work as you expect.这是因为它正在执行整数除法。对于
a = 1459
、b = 1500
:简单的解决方法是通过使用浮点数作为参数之一来强制其执行浮点除法:
It's because it's performing integer division. With
a = 1459
,b = 1500
:The easy fix is to force it to perform floating point division instead by using a float as one of the arguments:
使用整数除法时期望出现双精度数肯定是本书中最古老的问题。 ;)
您的回合不会执行任何操作,因为您的整数除法会产生整数结果。
Expecting a double when using integer division has to be the oldest gotcha in the book. ;)
Your round doesn't do anything as your integer divisions produce integer result.
预期结果是 17。
我怀疑您不想进行整数除法。因此,您必须将
3
和10
替换为3.0
和10.0
。The expected outcome is 17.
I suspect you do not want to have integer division. Therefore you must replace
3
and10
by3.0
and10.0
.您必须记住要考虑到这样一个事实:在 Java 中,当一个整数除以另一个整数时,结果是一个整数,而不是浮点数(任何余数都会被丢弃)。例如
6/4 == 1
,而不是1.5
。方法(1459, 1500)
You must remember to take into account the fact that when an integer is divided by another integer in Java, the result is an integer, not a float (any remainder is dropped). For example
6/4 == 1
, not1.5
.method(1459, 1500)