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.

30 Part I: Introduction to C++ ProgrammingLopping off the fractional part of a number is called truncation, or roundingoff. For many applications, truncation isn’t a big deal. Some folks might considerits results reasonable (not mathematicians or bookies, of course), butinteger truncation can create math mayhem in computer programs. Considerthe following equivalent formulation:int nAverage; int nValue1; int nValue2; int nValue3;nAverage = nValue1/3 + nValue2/3 + nValue3/3;Plugging in the same 1, 2, and 2 values, the resulting value of nAverage is (talkabout logical-but-unreasonable) 0. To see how this can occur, consider that13 truncates to 0, 23 truncates to 0, and 23 truncates to 0. The sum of 0, 0, and0 is zero. (Sort of like that old song: “Nothing from nothing leaves nothing, yagotta be something . . .”) You can see that integer truncation can be completelyunacceptable.Limited rangeA second problem with the int variable type is its limited range. A normalint variable can store a maximum value of 2,147,483,647 and a minimum valueof –2,147,483,648 — roughly from positive 2 billion to negative 2 billion, for atotal range of about 4 billion.Two billion is a very large number: plenty big enough for most uses. But it’snot large enough for some applications — for example, computer technology.In fact, your computer probably executes faster than 2 gigahertz, dependingupon how old your computer is. (Giga is the prefix meaning billion.) A singlestrand of communications fiber — the kind that’s been strung from one endof the country to the other — can handle way more than 2 billion bits persecond.C++ offers a little help by allowing you declare an integer to be unsigned, meaningthat it cannot be negative. An unsigned int value type can represent anumber from 0 to 4,294,967,295, should the need arise for some unimaginablereason.You can declare a variable simply unsigned. The int is implied.Solving the truncation problemThe limitations of int variables can be unacceptable in some applications.Fortunately, C++ understands decimal numbers. A decimal number can havea nonzero fractional part. (Mathematicians also call those real numbers.)Decimal numbers avoid many of the limitations of int type integers. Noticethat a decimal number “can have” a nonzero fractional part. In C++, thenumber 1.0 is just as much a decimal number as 1.5. The equivalent integer iswritten simply as 1. Decimals numbers can also be negative, like –2.3.

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

Saved successfully!

Ooh no, something went wrong!