我总是记不住电话号码。我需要一个记忆规则。
当前回答
最简单的方法是查看std::numeric_limits< int >::max()
例如(来自MSDN),
// numeric_limits_max.cpp
#include <iostream>
#include <limits>
using namespace std;
int main() {
cout << "The maximum value for type float is: "
<< numeric_limits<float>::max( )
<< endl;
cout << "The maximum value for type double is: "
<< numeric_limits<double>::max( )
<< endl;
cout << "The maximum value for type int is: "
<< numeric_limits<int>::max( )
<< endl;
cout << "The maximum value for type short int is: "
<< numeric_limits<short int>::max( )
<< endl;
}
其他回答
我在c#中做了几个天才的方法,你可以在你的生产环境中利用:
public static int GetIntMaxValueGenius1()
{
int n = 0;
while (++n > 0) { }
return --n;
}
public static int GetIntMaxValueGenius2()
{
int n = 0;
try
{
while (true)
n = checked(n + 1);
}
catch { }
return n;
}
永远不要忘记任何类型的最大值:
如果它有32位,最大的可能值将是带有数字1的32位:
结果将是十进制的4294967295:
但是,由于也有负数的表示,4294967295除以2,得到2147483647。
因此,一个32位整数能够表示-2147483647到2147483647
它是10位数字,所以假装它是一个电话号码(假设你在美国)。214-748-3647。我不建议调用它。
请记住,2^(10*x)大约是10^(3*x) -您可能已经习惯了千字节/千字节等。那就是:
2^10 = 1024 ~= one thousand
2^20 = 1024^2 = 1048576 ~= one million
2^30 = 1024^3 = 1073741824 ~= one billion
由于int型使用31位(符号为+ ~1位),所以只需将2^30乘以2就可以得到大约20亿。对于使用32位的unsigned int,再次翻倍为40亿。当然,误差系数越大,但你不需要记住准确的值(如果你需要,你应该使用一个预定义的常量)。这个近似值足够好,可以用来注意到什么时候某样东西可能会危险地接近溢出。
无论如何,取这个正则表达式(它确定字符串是否包含一个十进制形式的非负整数,也不大于Int32.MaxValue)
[0-9] {1, 9} | [0, 1] [0-9] {1, 8} | 20 [0-9] {1, 8} | 21 [0, 3] [0-9] {1, 7} | 214 [0-6] [0-9] {1, 7} | 2147 [0, 3] [0-9] {1, 6} | 21474 [0] [0-9] {1, 5} | 21 4748 [2-0] [0-9] {1, 4} | 2147483 [0 to 5] [0-9] {1, 3} | 21474836 [0, 3] [0-9] {1, 2} | 214748364 [0]
也许能帮你记起来。
推荐文章
- 在Android上将字符串转换为整数
- 将整数转换为字符串,以逗号表示千
- 在每个列表元素上调用int()函数?
- Java整数到字节数组
- 如何优雅地检查一个数字是否在一个范围内?
- 从整数列表中,求出最接近给定值的数
- 在python中将整数转换为二进制
- 如何将对象转换为int型
- Java如何处理整数下溢和溢出,如何检查它?
- 在Java和c#中,int和Integer的区别是什么?
- 是否有一种方法可以迭代一系列整数?
- 为什么整数除法产生一个浮点数而不是另一个整数?
- 在python中最安全的方法将浮点数转换为整数?
- 我如何工作围绕JavaScript的parseInt八进制行为?
- 将两个整数以唯一且确定的方式映射为一个整数