11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 2: Declaring Variables Constantly 31When you declare variables in C++ that are decimal numbers, you identify themas double precision floating-point values. (Yes, there is such a critter as a“single precision floating-point variable,” but stick with me here.) The termfloating-point means the decimal point is allowed to float back and forth, identifyingas many “decimal places” as necessary to express the value. Floatingpointvariables are declared in the same way as int variables:double dValue1;From this point forward, the variable dValue1 is declared to be a double. Oncedeclared, you cannot change the type of a variable. dValue1 is now a doubleand will be a double for the remainder of its natural instructions. To see howfloating-point numbers fix the truncation problem inherent with integers, convertall the int variables to double. Here’s what you get:double dValue;dValue = 1.0/3.0 + 2.0/3.0 + 2.0/3.0;is equivalent todValue = 0.333... + 0.666... + 0.666...;which results in the valuedValue = 1.666...;I have written the value 1.6666 . . . as if the number of trailing 6s goes onforever. This is (not necessarily) the case. There’s a limit to the number of digitsof accuracy of a double variable — but it’s a lot more than I can keep track of.The programs IntAverage and FloatAverage are available on the enclosedCD in the CPP_Programs\Chap02 directory to demonstrate this averagingexample.Looking at the limits of floating-point numbersAlthough floating-point variables can solve many calculation problems suchas truncation, they have some limitations themselves — in effect, the reverseof those associated with integer variables. double variables can’t be used ascounting numbers, they’re more difficult for the computer to handle, and theyalso suffer from round-off error (though not nearly to the same degree as intvariables).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!