1 使用数据类型的时候,不同的编译环境,数据的字节最值有时候是不一样的。
2 提前测试一下各种数据类型的最值,避免以后出现神奇bug找了半天发现是越界。
3 源码展示:
#include<iostream>
#include<limits.h>
using namespace std;
int main() {
cout << "char \t" << sizeof(char) << "字节 \t" << endl;
cout << "int \t" << sizeof(int) << "字节 \t" << "最小值:\t"<<numeric_limits<int>::min() << " 最大值:\t"<<numeric_limits<int>::max() << endl;
cout << "long int\t" << sizeof(long int) << "字节 \t" << "最小值:\t" << numeric_limits<long int>::min() << " 最大值:\t" << numeric_limits<long int>::max() << endl;
cout << "long long int\t" << sizeof(long long int) << "字节 \t" << "最小值:\t" << numeric_limits<long long int>::min() << " 最大值:\t" << numeric_limits<long long int>::max() << endl;
cout << "float \t" << sizeof(float) << "字节 \t" << "最小值:\t" << numeric_limits<float>::min() << " 最大值:\t" << numeric_limits<float>::max() << endl;
cout << "long float \t" << sizeof(long float) << "字节 \t" << "最小值:\t" << numeric_limits<long float>::min() << " 最大值:\t" << numeric_limits<long float>::max() << endl;
cout << "double \t" << sizeof(double) << "字节 \t" << "最小值:\t" << numeric_limits<double>::min() << " 最大值:\t" << numeric_limits<double>::max() << endl;
cout << "long double \t" << sizeof(long double) << "字节 \t" << "最小值:\t" << numeric_limits<long double>::min() << " 最大值:\t" << numeric_limits<long double>::max() << endl;
getchar();
}
4 结果展示:
5 心得:
1)int 和long int 都是四个字节,好不好玩,神不神奇。
2)double 和long double 也是一样,都是8个字节。
3)一个字不一定是两个字节(取决于机器字长的位数,比如机器字长为16位,一个字等于两个字节。机器字长为32位,一个字等于4个字节),一个字节是8位(8个0 1数字组合 是2^8)。
4)例如4个字节是2^32=4,,294,967,296,有正负,所以还要对半分,除2等于2,147,483,648 和计算机计算一致。
5)如有误之处,欢迎指正。