C++过早地长满
我在使用 C++ 时遇到了一个奇怪的问题,其中长数据类型早在应该溢出的时候就溢出了。我正在做的(到目前为止已经成功)是让整数表现得像浮点数,以便范围 [-32767,32767] 映射到 [-1.0,1.0]。它的失败之处在于代表浮点数大于 1.0 的较大参数:
inline long times(long a, long b) {
printf("a=%ld b=%ld ",a,b);
a *= b;
printf("a*b=%ld ",a);
a /= 32767l;
printf("a*b/32767=%ld\n",a);
return a;
}
int main(void) {
printf("%ld\n",times(98301l,32767l));
}
我得到的输出是:
a=98301 b=32767 a*b=-1073938429 a*b/32767=-32775
-32775
所以 times(98301,32767) 类似于 3.0*1.0。当 times 参数小于 32767 (1.0) 时,此代码可以完美运行,但使用上述参数的任何中间步骤都不应溢出 64 位 long。
有什么想法吗?
I'm having a bizarre problem with C++ where the long data type is overflowing long before it should. What I'm doing (with success so far) is to have integers behave like floats, so that the range [-32767,32767] is mapped to [-1.0,1.0]. Where it stumbles is with larger arguments representing floats greater than 1.0:
inline long times(long a, long b) {
printf("a=%ld b=%ld ",a,b);
a *= b;
printf("a*b=%ld ",a);
a /= 32767l;
printf("a*b/32767=%ld\n",a);
return a;
}
int main(void) {
printf("%ld\n",times(98301l,32767l));
}
What I get as output is:
a=98301 b=32767 a*b=-1073938429 a*b/32767=-32775
-32775
So times(98301,32767) is analogous to 3.0*1.0. This code works perfectly when the arguments to times are less than 32767 (1.0), but none of the intermediate steps with the arguments above should overflow the 64 bits of long.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
long 不一定是 64 位。尝试“长长”。
long is not necessarily 64 bits. try 'long long' instead.
long
类型不一定是 64 位。如果您使用的是 32 位体系结构(至少在 MS Visual c++ 上),则long
类型为 32 位。使用sizeof(long)
检查一下。还有long long
数据类型可能会有所帮助。The type
long
is not necessarily 64 bits. If you are on the 32 bit architecture (at least on MS Visual c++), thelong
type is 32 bits. Check it out withsizeof (long)
. There is also thelong long
data type that may help.您可能有 32 位长整型。尝试使用
long long
代替。98301 * 32767 = 3221028867,而32位长溢出在2147483648
You probably have 32-bit longs. Try using
long long
instead.98301 * 32767 = 3221028867, while a 32-bit long overflows at 2147483648
C 标准仅保证
long
至少为 32 位(大多数 32 位平台上实际上都是这种情况)。如果您需要 64 位,请使用
long long
。它保证至少保存 64 位。The C standard only guarantees that
long
will have at least 32 bit (which is actually the case on most 32bit platforms).If you need 64 bit, use
long long
. It's guaranteed to hold at least 64 bit.