欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

理解C语言中的浮点数类型

最编程 2024-08-08 20:51:36
...
In C, floating point types are used to represent real numbers (numbers with fractional parts) and are typically implemented following the IEEE 754 standard. The most common floating point types in C are float, double, and long double. These types differ in their precision and range, which is a result of how they represent a number using three components: the sign bit, the exponent, and the mantissa (or significand).
Components of a Floating Point Number in IEEE 754
Sign Bit:
This is a single bit representing the sign of the number.
0 indicates a positive number, and 1 indicates a negative number.
Exponent:
The exponent is used to represent the scale (or magnitude) of the number.
It is stored in “biased” form, meaning that a fixed bias is added to the actual exponent value to get a non-negative value stored in the exponent field. This bias is , where is the number of bits in the exponent.
For example, in a 32-bit float, 8 bits are used for the exponent, and the bias is 127 = .
Mantissa (Significand):
The mantissa represents the precision bits of the number. It’s the fractional part of the number, normalized such that its range is just below 1 to just less than 2 (in binary, this means it starts with 1.).
However, the leading 1 is implicit and usually not stored (known as the “hidden bit” assumption). This is due to the fact that normalized numbers always start with 1, and hence it can be omitted to save storage space.
The remaining part of the mantissa is what is actually stored and represents the fraction.
Floating Point Types in C
float:
Typically 32 bits: 1 bit for sign, 8 bits for exponent, and 23 bits for mantissa.
Precision of about 6-7 decimal digits.
double:
Typically 64 bits: 1 bit for sign, 11 bits for exponent, and 52 bits for mantissa.
Precision of about 15-16 decimal digits.
long double:
Size and precision can vary depending on the system and compiler, but it is at least as large as double.
Often 80 or 128 bits on many systems, with varying distribution among sign, exponent, and mantissa.
Considerations
Floating point numbers can represent a very wide range of values, but they do so with limited precision. Operations on floating point numbers can introduce rounding errors.
Special values are represented in IEEE 754, such as Infinity (positive and negative) and NaN (Not a Number), which result from operations that have undefined or unrepresentable results in real numbers.
Due to their inexact nature, floating point numbers should not be used where exact results are required, such as in monetary calculations.