事实上,某种数据类型的长度在平台上是不同的。但是现在让我们说float 和int 是相同的,4 个字节。
4 字节等于 32 位,二进制的范围是
00000000000000000000000000000000
到
1111111111111111111111111111111
此时,我们应该回忆一下几何序列,上面的和等于
2^32 + 2^31 + ... + 2^1 + 2^0 = 2147483648
注意,C 重新定义了从数学到语言的范围,如 unsigned 或 signed 通过 shift。
也就是说它也可以定义float。
看到EEEEEEEMMMMMMMMMMMMMMMMMMMMMMMMM
S = 符号(1 位)
E = 指数(8 位)
M = 尾数(23 位)
值计算遵循IEEE-754,这并不容易,但我们可以在754 converter尝试:)
现在,范围,(见指数技巧?它的意思是 E-127,减号!)
0 00000001 00000000000000000000000
到
0 11111110 1111111111111111111111
数学,
2^-126 * 1.00000000000000000000000 = 1.1754943508222875 × 10^-38
到
2^(128) * 1.1111111111111111111111 = 3.7809151880104275 x 10^38
注意尾数有一个隐藏的 1,否则你总是得到 0:
最后机器一开始就是为了救命,所以在我们选择数据类型之前,我们最好从头文件中检查范围,例如
#include <stdio.h>
#include <limits.h>
#include <float.h>
int main()
{
printf("Range of signed char %d to %d\n", SCHAR_MIN, SCHAR_MAX);
printf("Range of unsigned char 0 to %d\n\n", UCHAR_MAX);
printf("Range of signed short int %d to %d\n", SHRT_MIN, SHRT_MAX);
printf("Range of unsigned short int 0 to %d\n\n", USHRT_MAX);
printf("Range of signed int %d to %d\n", INT_MIN, INT_MAX);
printf("Range of unsigned int 0 to %lu\n\n", UINT_MAX);
printf("Range of signed long int %ld to %ld\n", LONG_MIN, LONG_MAX);
printf("Range of unsigned long int 0 to %lu\n\n", ULONG_MAX);
// In some compilers LLONG_MIN, LLONG_MAX
printf("Range of signed long long int %lld to %lld\n", LLONG_MIN, LLONG_MAX);
// In some compilers ULLONG_MAX
printf("Range of unsigned long long int 0 to %llu\n\n", ULLONG_MAX);
printf("Range of float %e to %e\n", FLT_MIN, FLT_MAX);
printf("Range of double %e to %e\n", DBL_MIN, DBL_MAX);
printf("Range of long double %e to %e\n", LDBL_MIN, LDBL_MAX);
return 0;
}