作者ric2k1 (Ric)
看板EE_DSnP
标题Re: [问题] 关於变数数值的问题
时间Sun Oct 21 10:06:38 2007
※ 引述《Knossos (苍天已死黄天当立)》之铭言:
: 首先,我用sizeof()的函数,找出long long int的大小为8,照理说,最大正数应该
: 可以储存2^63-1,可是电脑却只可以储存2^31-1,这是为什麽呢?其他记忆体被吃掉了吗
: 上面的问题牵扯到下面这个问题:
: #include <iostream>
: using namespace std;
: int main()
: {
: unsigned int a;
: unsigned int b;
: a = , b = 2147483647;
: //2 ^ 32 = 2147483648
: cout << a*b << endl;
: system("pause");
: return 0;
: }
: 我现在操控a的数值来影响a*b的结果。我发现,当a=1 or 2时,结果是正确的,萤幕
: 上显示我要的结果。可是当a>3後,乘积却始终不正确。
: 如果说是因为两个的乘积超过unsigned int的记忆体容量,那为什麽乘以2时会对?
: 还是说,两个unsigned int的四则运算,最多只能显示出最大正数的两倍?
: 这个问题该如何解决?
UINT_MAX = 2^32 - 1 = 4294967295
2147483648 = 2^31
Because a is an unsigned, and b is an unsigned,
a*b will also be an unsigned int.
So the max value of a*b will be 2^32-1.
So when a = 3, it overflows and will be truncated.
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 59.121.134.53
1F:→ Knossos:啊~我搞错了...sorry! 那上一个问题,long long int呢? 10/21 20:30