...
Because 0.1f
is rounded to the nearest value that can be represented in the value set of the float
type, the actual quantity added to x
on each iteration is somewhat larger than 0.1
. Consequently, the loop executes only nine times and typically fails to produce the expected output.
...
This noncompliant code example uses a floating-point loop counter that is incremented by an amount that is typically too small to change its value given the precision.
...
This compliant solution uses an integer loop counter from which the floating-point value is derived. Additionally, it uses a double
to ensure that the available precision suffices to represent the desired values. The solution also runs in FP-strict mode to guarantee portability of its results. See NUM06-J for more information.
Code Block | ||
---|---|---|
| ||
for (int count = 1; count <= 10; count += 1) { double x = 100000000.0 + count; /* ... */ } |
...
FLP30-C. Do not use floating point variables as loop counters | ||||
FLP30-CPP. Do not use floating point variables as loop counters | ||||
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="553d9ad7626c3beb-87cbf9fb-427345b3-ab8fa952-280f2186d2275bc5abea53f3"><ac:plain-text-body><![CDATA[ | [ISO/IEC TR 24772:2010 | http://www.aitcnet.org/isai/] | Floating-point Arithmetic [PLF] | ]]></ac:plain-text-body></ac:structured-macro> |
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="5503b272a71a7292-d0866301-462544db-8556beeb-4d8028f9797d25b1d3e89e90"><ac:plain-text-body><![CDATA[ | [[Bloch 2005 | AA. Bibliography#Bloch 05]] | Puzzle 34, Down for the count | ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="d4e5e1a6d1ed75cc-2e4b1b9b-4c504748-933fb447-131de01b0e472f68e1f0eca7"><ac:plain-text-body><![CDATA[ | [[JLS 2005 | AA. Bibliography#JLS 05]] | [§4.2.3, Floating-Point Types, Formats, and Values | http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3] | ]]></ac:plain-text-body></ac:structured-macro> |
...