关于浮点数和浮点数的溢出问题×整数
1)这是不可溢出的吗?
long long v1, v2, result;
[..]
result = ((long double) v1 / v2) * 1000000LL;
1.a) 我可以省略常数上的 LL 吗?以及为什么。
2)或者这种没有浮动的变体可以吗?
long long l1, l2, result;
[..]
result = (1000000 * (v1 / v2) + v1 % v2);
2.a) 哪一个的管理费用更多?第一个还是这个例子?
3)浮点数是否会溢出,或者只是换行为“正常”值?
1) Is this unoverflowable?
long long v1, v2, result;
[..]
result = ((long double) v1 / v2) * 1000000LL;
1.a) Can I leave out the LL on the constant? And why.
2) Alternatively is this variation without a float ok?
long long l1, l2, result;
[..]
result = (1000000 * (v1 / v2) + v1 % v2);
2.a) Which has more overheads? The 1st or this example?
3) Can floats ever overflow, or just wrap to 'sane' values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,
因为 (float)v1/v2 = ab.cdef。 // 其中 cdef 可以变化。
您的第二个实现也可能导致溢出
如果 v1 = 2^15 且 v2 = 1
,那么如果您正在寻找溢出和安全性,您应该始终检查
2^18/Constant,在本例中为 1000000
,因此
这将是任何黑客证明。
希望这有帮助
Firstly
Because (float)v1/v2 = ab.cdef. // where cdef can vary.
Your second implementation can also cause overflow
if v1 = 2^15 and v2 = 1
so if you are looking for overflow and security you should always check
like 2^18/Constant which is 1000000 in this case
so
This would be any hack proof.
Hope This helps
是的,如果 v1 = 1000000000000000 且 v2 = 1,示例 (1) 中的结果很容易溢出。您不需要该常量上的 LL,因为它足够小,可以放入
int
(在大多数实现下,无论如何)。(2) 如果 v1 和 v2 正如我所给出的那样,那么它可能会像示例 1 一样溢出。
第一个示例更昂贵,因为浮点算术比整数算术更昂贵。
(3) 浮点数肯定可能溢出,其后果取决于实现。
正如 Arjit 所指出的,您可以通过在执行计算之前检查 v1 的值来防止溢出。如果 v1 可能为负,您还需要检查负版本,也许以下可能会更好...
如果您确实遇到了限制,您可以通过将变量声明为
来给自己多一点空间未签名
。稍后 - 编辑以纠正 Arjit 指出的错误。
Yes, the result in example (1) could easily overflow if, say, v1 = 1000000000000000 and v2 = 1. You don't need the LL on that constant because it is small enough to fit into an
int
(under most implementations, in any case).(2) That can overflow just as well as example 1 if v1 and v2 are as I have given them.
The first example is more expensive as floating point arithmetic is more expensive than integer arithmetic.
(3) Floats may certainly overflow and the consequences are implementation dependent.
As Arjit has pointed out, you can prevent an overflow by checking the value of v1 before performing the calculation. If v1 could be negative you would also need to check the negative version, and perhaps the following might be better...
If you are really up against the limit you could give yourself a little more headroom by declaring the variables to be
unsigned
.Later - edit to correct mistake pointed out by Arjit.