unsigned long 大于 0xFFFFFFFF
unsigned long larger than 0xFFFFFFFF
如果 unsigned long 最大值为 4294967295,测试程序如何得出 4294967297?
#include <iostream>
using namespace std;
unsigned long millis_diff(unsigned long then, unsigned long now) {
return now < then ? now + then : now - then;
}
int main()
{
unsigned long now = 2;
unsigned long then = 4294967295; //unsigned long maximum value
unsigned long diff = millis_diff(then, now);
cout << diff;
return 0;
}
原因是您的编译器似乎定义 unsigned long int
的方式与定义 unsigned long long int
的方式相同:)
这是一个演示程序
#include <iostream>
#include <limits>
int main()
{
std::cout << "sizeof( unsigned long ) = " << sizeof( unsigned long ) << '\n';
std::cout << "The maximum values is " << std::numeric_limits<unsigned long>::max() << '\n';
}
它的输出是
sizeof( unsigned long ) = 8
The maximum values is 18446744073709551615
How test program can result 4294967297 if unsigned long maximum is 4294967295?
鉴于前提,不能。
但是,不能保证 unsigned long
最大值恰好为 4'294'967'295,因此您的前提可能无效。该最大值对应于 32 位数可以表示的最大值。 32 是 (unsigned
) long
所需的 最小 宽度,但它可能比这更宽。
特别是一些64位系统,典型的有unsigned long
个64位,最大值为18'446'744'073'709'551'615.
如果 unsigned long 最大值为 4294967295,测试程序如何得出 4294967297?
#include <iostream>
using namespace std;
unsigned long millis_diff(unsigned long then, unsigned long now) {
return now < then ? now + then : now - then;
}
int main()
{
unsigned long now = 2;
unsigned long then = 4294967295; //unsigned long maximum value
unsigned long diff = millis_diff(then, now);
cout << diff;
return 0;
}
原因是您的编译器似乎定义 unsigned long int
的方式与定义 unsigned long long int
的方式相同:)
这是一个演示程序
#include <iostream>
#include <limits>
int main()
{
std::cout << "sizeof( unsigned long ) = " << sizeof( unsigned long ) << '\n';
std::cout << "The maximum values is " << std::numeric_limits<unsigned long>::max() << '\n';
}
它的输出是
sizeof( unsigned long ) = 8
The maximum values is 18446744073709551615
How test program can result 4294967297 if unsigned long maximum is 4294967295?
鉴于前提,不能。
但是,不能保证 unsigned long
最大值恰好为 4'294'967'295,因此您的前提可能无效。该最大值对应于 32 位数可以表示的最大值。 32 是 (unsigned
) long
所需的 最小 宽度,但它可能比这更宽。
特别是一些64位系统,典型的有unsigned long
个64位,最大值为18'446'744'073'709'551'615.