划分整数类型 - 结果是可预测的吗?
我有一个 64 位长,我想向下舍入到最接近的 10,000,所以我正在做一个简单的:
long myLong = 123456789
long rounded = (myLong / 10000) * 10000; //rounded = 123450000
这似乎符合我的预期,但因为我不是 100% 了解整数类型如何划分的内部原理,我只是有点担心在某些情况下这可能无法按预期工作。
这在非常大的数字/边缘情况下仍然有效吗?
I have a 64-bit long that I want to round down to the nearest 10,000, so I am doing a simple:
long myLong = 123456789
long rounded = (myLong / 10000) * 10000; //rounded = 123450000
This appears to do what I expect, but as I'm not 100% on the internals of how integer types get divided, I am just slightly concerned that there may be situations where this doesn't work as expected.
Will this still work at very large numbers / edge cases?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,只要中间结果或其他结果没有超过
long.MaxValue
,它就会起作用。要明确您的常量,您可以在末尾使用
L
说明符,例如123456789L
。对于像这样的简单计算,我可以建议 Microsoft 的 Pex ( http://research.microsoft .com/en-us/projects/pex/ ),它查找边缘情况并测试它们。这是一个简洁的示例,但如果您根据不确定的事情构建大量逻辑,那么它是一个很棒的工具。
Yes, it will work, so long as no result, intermediate or otherwise, exceeds
long.MaxValue
.To be explicit about your constants you could use the
L
specifier at the end, e.g.123456789L
.For straightforward calculations like this, can I suggest Pex from Microsoft ( http://research.microsoft.com/en-us/projects/pex/ ), which looks for edge cases and tests them. This is a clean-cut example, but if you were building up lots of logic based on things you are unsure of, it's a great tool.
是的,它会起作用。整数除法的语义保证了您的期望。
但是,最好为您的特定用例(包括边缘情况)编写一些测试。这会让你放心。
Yes, it will work. The semantics of integer division guarantee what you expect.
However it may be good to write some tests for your specific use case, including edge cases. This will reassure you.