11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 2: Declaring Variables Constantly 29int x;x = 1;The variable type int is the C++ equivalent of an integer — a number thathas no fractional part. (Integers are also known as counting numbers or wholenumbers.)Integers are great for most calculations. You can make it up through most (ifnot all) of elementary school with integers. It isn’t until you reach age 11 orso that they start mucking up the waters with fractions. The same is true inC++: More than 90 percent of all variables in C++ are declared to be of type int.Unfortunately, int variables don’t always work properly in a program. If (forexample) you worked through the temperature-conversion program in Chapter1, the program has a potential problem — it can only handle integer temperatures— whole numbers that don’t have a fractional part. This limitationof using only integers doesn’t affect daily use because it isn’t likely that someone(other than a meteorologist) would get all excited about entering a fractionaltemperature (such as 10.5 degrees). The lurking problem is not at allobvious: The conversion program lops off the fractional portion of temperaturesthat it calculates, and just keeps going without complaint. This can resultin a lapse of accuracy that can be serious — for example, you wouldn’t wantto come up a half mile short of the runway on your next airplane trip due to anavigational round-off.Reviewing the limitationsof integers in C++The int variable type is the C++ version of an integer. int variables suffer thesame limitations as their counting-number integer equivalents in math do.Integer round-offConsider the problem of calculating the average of three numbers. Given threeint variables — nValue1, nValue2, and nValue3 — an equation for calculatingthe average isint nAverage; int nValue1; int nValue2; int nValue3;nAverage =(nValue1 + nValue2 + nValue3) / 3;Because all three values are integers, the sum is assumed to be an integer.Given the values 1, 2, and 2, the sum is 5. Divide that by 3, and you get 1 2 ⁄3, or1.666. Given that all three variables nValue1, nValue2, and nValue3 are integers,the sum is also assumed to be an integer. The result of the division is alsoan integer. The resulting value of nAverage is unreasonable but logical: 1.

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

Saved successfully!

Ooh no, something went wrong!