简体   繁体   中英

Is the floating-point literal “.1” the same as “0.1” in C?

在C程序的源文本中, .10.1是否具有相同的值?

.1 represents one-tenth, the same as 0.1 does. However, due to a lack of strictness in the C standard, .1 and 0.1 do not necessarily convert to the same internal value, per C 2018 6.4.4.2 5. They will be equal in all compilers of reasonable quality. (6.4.4.2 5 says “All floating constants of the same source form shall convert to the same internal format with the same value.” Footnote 77 gives examples of source forms that have the same mathematical values but that do not necessarily convert to the same internal value.)

Floating-point constants in source text are converted to an internal format. Most commonly, a binary-based format is used. Most decimal numerals, including .1, are not exactly representable in binary floating-point. So, when they are converted, the result is rounded (in binary) to a representable value. In typical C implementations, .1 becomes 0.1000000000000000055511151231257827021181583404541015625.

All good compilers will convert .1 and 0.1 to the same value. The reason the C standard is lax about this is that other floating-point literals, involving exponents or many digits, were difficult (in some sense) to convert to binary floating-point with ideal rounding. Historically, there were C implementations that fudged the conversions. The C standard accommodated these implementations by not making strict requirements about handling of floating-point values. (Today, good algorithms are known, and any good compiler ought to convert a floating-point literal to the nearest representable value, with ties to the even low digit, unless the user requests otherwise.)

So, the C standard does not guarantee that .1 and 0.1 have the same value. However, in practice, they will.

Eric's answer is correct if you're just talking about the baseline C standard, which makes basically no guarantees about floating point; 1.0==42.0 is a valid implementation choice. But this is not very helpful.

If you want any reasonable floating point behavior in C, you want an implementation that supports Annex F (the alignment of IEEE floating point semantics with C), an optional part of the standard. You can tell if your implementation supports (or claims to support) Annex F by checking for the predefined macro __STDC_IEC_559__ .

Assuming Annex F, the interpretation of floating point literals is not up for grabs, and .1 and 0.1 will necessarily be the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM