A Caution about Using Type float or double for Monetary Amounts

Lines 10–12 declare the double variables amount, principal and rate. We did this for simplicity because we’re dealing with fractional parts of dollars, and we need a type that allows decimal points in its values. Unfortunately, this can cause trouble. Here’s a simple explanation of what can go wrong when using float or double to represent dollar amounts (assuming setprecision(2) is used to specify two digits of precision when printing): Two dollar amounts stored in the machine could be 14.234 (which prints as 14.23) and 18.673 (which prints as 18.67). When these amounts are added, they produce the internal sum 32.907, which prints as 32.91. Thus your printout could appear as

  14.23
+ 18.67
-------
  32.91

but a person adding the individual numbers as printed would expect the sum 32.90! You’ve been warned! [Note: Some third-party vendors sell C++ class libraries that perform precise monetary calculations.]

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.157.248