0. Introduction
This section is "[C ++] common pitfalls numerical value of the type overflow and truncation (1)" supplement focuses on floating-point values overflow.
1. Knowledge
(1) floating-point data in the following ranges:
Single-precision | float | 3.4 * 10^-38 ~ 3.4 * 10^38 |
Double | double | 1.7 * 10^-308 ~ 1.7 * 10^308 |
Long double | long double | 1.7 * 10^-308 ~ 1.7 * 10^308 |
C ++ and the absence of uniform accuracy of various types of data, scale and proportion of the number of bytes in memory, various C ++ compiler system to make arrangements according to their circumstances [1]. In VC6.0, float, double, long double accounting 4,8,8 bytes.
(2) is converted into a binary floating-point number
Float into an integer part and a fractional part, integer part according to " In addition to taking more than two reverse writing rules" will be converted to a binary floating-point written on the left of the decimal part in accordance with the " by-two rounded positive sequence written law" will be convert it to a binary floating-point written on the right side of [2]. Examples are as follows:
2. floating-point value range overflow
// ConsoleApplication1.cpp: custom console application entry point.
//
#include " stdafx.h "
#include <iostream>
#include <iostream>
#include <the cstddef>
#include <typeinfo>
int main () {
system("color 3f");
float fTest1 = 3.4e33;
float fTest2 = 3.4e38;
float fTest3 = 3.4e39;
printf("fTest1: %d: Dec: %d; Hex: %x; size: %d\n", fTest1, fTest1, fTest1, sizeof(fTest1));
printf("fTest2: %d: Dec: %d; Hex: %x; size: %d\n", fTest2, fTest2, fTest2, sizeof(fTest2));
printf("fTest3: %d: Dec: %d; Hex: %x; size: %d\n", fTest3, fTest3, fTest3, sizeof(fTest3));
//std::cout << fTest1 << std::endl;
system("pause");
return 0;
}
operation result:
Here, two questions arise:
(1) fTest2 and fTest3 appeared overflow;
(2) fTest2 与 fTest3 溢出后,并没有使用多余的位来表示,“【C++】常见易犯错误之数值类型取值溢出与截断(3)”中提到,short 型溢出使用多余位来表示;但这里显然没有出现这种情况。
(2) 尚未解决,标红
参考文献
[1] 谭浩强.C++程序设计[M].北京:清华大学出版社,P18.
[2] 浮点数转二进制与浮点数据在计算机中的表示. https://blog.csdn.net/csdn1829/article/details/79376073.