Practices
  Home arrow Practices arrow Page 2 - Basic Data Types and Calculations
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PRACTICES

Basic Data Types and Calculations
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 13
    2005-09-08


    Table of Contents:
  • Basic Data Types and Calculations
  • Performing Simple Calculations
  • Try It Out: Integer Arithmetic in Action
  • Try It Out: Fixing the Appearance of the Output
  • Try It Out: Using Integer Variables
  • The Assignment Operator
  • Incrementing and Decrementing Integers
  • Numerical Functions for Integers
  • Floating-Point Operations
  • Try It Out: Floating-Point Arithmetic
  • Try It Out: Yet More Output Manipulators
  • Working with Characters
  • Functional Notation for Initial Values
  • Exercises

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Basic Data Types and Calculations - Performing Simple Calculations
    ( Page 2 of 14 )

    To begin with, let’s get some bits of terminology out of the way. An operation (such as a mathematical calculation) is defined by an operator— + for addition, for example, or * for multiplication. The values that an operator acts upon are called operands, so in an expression such as 2*3 , the operands are 2 and 3 .

    + for addition, for example, or * for multiplication. The values that an operator acts upon are called , so in an expression such as 2*3 , the operands are 2 and 3 . To begin with, let’s get some bits of terminology out of the way. An operation (such as a mathematical calculation) is defined by an — + for addition, for example, or * for multiplication. The values that an operator acts upon are called , so in an expression such as 2*3, the operands are 2 and 3.

    Because the multiplication operator requires two operands, it is called a binary operator. Some other operators only require one operand, and these are called unary operators. An example of a unary operator is the minus sign in –2 . The minus sign acts on one operand—the value 2—and changes its sign. This contrasts with the binary subtraction operator in expressions such as 4 - 2 , which acts on two operands, the 4 and the 2 .

    Introducing Literals

    In C++, fixed values of any kind, such as 42 , or 2.71828 , or "Mark Twain" , are referred to as literals.In Chapter 1, when you were outputting text strings to the screen, you used a string literal—a constant defined by a series of characters between a pair of double quotes, of which "Mark Twain" is an example. Now you’ll investigate the types of literals that are numeric constants. These are the ordinary numbers you meet every day: your shoe size, the boiling point of lead, the number of angels that can sit on a pin—in fact, any defined number.

    There are two broad classifications of numeric constants that you can use in C++:

    • Integer literals are whole numbers and are written without a decimal point.
    • Floating-point literals (commonly referred to as floating-point numbers) are numbers that can be nonintegral values and are always written with a decimal point, or an exponent, or both. (You’ll look into exponents a little later on.)

    You use an integer when you’re dealing with what is evidently a whole number: the number of players on a team, for example, or the number of pages in a book. You use a floating-point value when the values aren’t integral: the circumference of a circle divided by its diameter, for example, or the exchange rate of the UK£ against the US$.

    Floating-point numbers are particularly helpful when you’re dealing with very small or very large quantities: the weight of an electron, the diameter of the galaxy, or the velocity of a bat out of hell, perhaps. The term “floating-point number” is used because while these values are represented by a fixed number of digits, called the precision, the decimal point “floats” and can be moved in either direction in relation to the fixed set of digits.

    Letting the Point Float

    Look at these two numbers:


    0.000000000000000000001234567                1.234567x10-21
    123456700000000000000000000.0                1.234567x10+26


     

    Both numbers have seven digits of precision, but they’re very different numbers, the first being an extremely small number and the second being very large. A floating-point representation of each number on the left is shown to its right. Multiplying the number by a power of 10 shifts the decimal point in the base number, 1.234567. This flexibility in positioning the decimal point allows a huge range of numbers to be represented and stored, from the very small to the very large, in a modest amount of memory.

    You’ll look at how to use integers first, as they’re the simpler of the two. You’ll come back to working with floating-point values as soon as you’re done with integers.

    Integer Literals

    You can write integer literals in a very straightforward way. Here are some examples:

    -123    +123     123      22333

    Here, the + and - signs in the first two examples are examples of the unary operators I mentioned earlier. You could omit the + in the second example, as it’s implied by default, but if you think putting it in makes things clearer, that’s not a problem. The literal +123 is the same as 123 . The fourth example is the number that you would normally write as 22,333, but you must not use commas within an integer literal. If you include a comma, the compiler is likely to treat your number as two numbers separated by the comma.

    You can’t write just any old integer value that you want, either. To take an extreme example, an integer with 100 digits won’t be accepted. There are upper and lower limits on integer literals, and these are determined by the amount of memory that’s devoted to storing each type of integer value on the computer that you’re using. I come back to this point a little later in the chapter when I discuss integer variables, and I also cover some further options for specifying integer literals.

    Of course, although I’ve written the examples of integer literals as decimal values, inside your computer they’re stored as binary numbers. Understanding binary arithmetic is quite important in programming, so in case you’re a little rusty on how binary numbers work, I’ve included a brief overview in Appendix E. If you don’t feel comfortable with binary and hexadecimal numbers, I suggest you take a look at the overview in Appendix E before continuing with the next section.

    Hexadecimal Integer Literals

    The previous examples of integer literals were decimal integers, but you can also write integers as hexadecimal values. To indicate that you’re writing a hexadecimal value, you prefix the number with 0x or 0X , so if you write 0x999 , you’re writing a hexadecimal number with three hexadecimal digits. Plain old 999 , on the other hand, is a decimal value with decimal digits, so the value will be completely different. Here are some more examples of integer literals written as hexadecimal values:

     


     

    Hexadecimal values 0x1AF 0x123 0xA 0xCAD 0xFF
    Corresponding decimal expression 1*162 1*162 10*160 12*162 15*161
      +10*161 +2*161   +10*161 +15*160
      +15*160 +3*160   +13*160  
    Decimal value 431 291 10 3245 255

     


     

    You’ll remember that in Chapter 1 you saw hexadecimal notation being used in escape sequences that defined characters. What you’re looking at here is different— you’re defining integers. You’ll come back to defining character literals later in this chapter.

    The major use for hexadecimal literals is when you want to define a particular pattern of bits. Because each hexadecimal digit corresponds to 4 bits in the binary value, it’s easy to express a particular pattern of bits as a hexadecimal literal. You’ll explore this further in the next chapter.

    Octal Integer Literals

    You can also write integers as octal values—that is, using base 8. You identify a number as octal by writing it with a leading zero. Here are some examples of octal values:

     


    Octal values                   0123  077  010101
    Corresponding decimal integers 83    63   4161


     

    Of course, octal numbers can only have digit values from 0 to 7. Octal is used very infrequently these days, and it survives in C++ largely for historical reasons from the time when there were computers around with a word length that was a multiple of 3 bits. However, it’s important to be aware of the existence of octal numbers, because if you accidentally write a decimal number with a leading zero, the compiler will try to interpret it as octal.

    CAUTION Don’t write decimal integer values with a leading zero. The compiler will interpret such values as octal (base 8), so a value written as 065 will be equivalent to 53 in decimal notation.

    As far as your compiler is concerned, it doesn’t matter which number base you choose when you write an integer value—ultimately, it will be stored in your computer as a binary number. The different ways available to you for writing an integer are there just for your convenience. You could write the integer value fifteen as 15 , as 0xF , or as 017 . These will all result in the same internal binary representation of the value, so you will choose one or other of the possible representations to suit the context in which you are using it.

    Integer Arithmetic

    The basic arithmetic operations that you can carry out on integers are shown in Table 2-1.

    Table 2-1. Basic Arithmetic Operations


    Operator  Operation
       +      Addition
       -      Subtraction
       *      Multiplication
       /      Division
       %      Modulus (the remainder after division)

     

    The operators in Table 2-1 work largely in the way you would expect, and notice that they are all binary operators. However, the division operation is slightly idiosyncratic, so let’s examine that in a little more detail. Because integer operations always produce an integer result, an expression such as 11/4 doesn’t result in a value of 2.75 . Instead, it produces 2 . Integer division returns the number of times that the denominator divides into the numerator. Any remainder is simply discarded. So far as the C++ standard is concerned, the result of division by zero is undefined, but specific implementations will usually have the behavior defined and, in some cases, will provide a programmatic means of responding to the situation, so check your product documentation.

    Figure 2-1 illustrates the different effects of the division and modulus operators.

     
    Figure 2-1.  Contrasting the division and modulus operators

    The modulus operator, % , which is sometimes referred to as the remainder operator, complements the division operator in that it provides a means for you to obtain the remainder after integer division if you need it. The expression 11%4 results in the value 3 , which is the remainder after dividing 11 by 4. When either or both operands of the modulus operator are negative, the sign of the remainder is up to the particular C++ implementation you’re using, so beware of variations between different systems. Because applying the modulus operator inevitably involves a division, the result is undefined when the right operand is zero.

    Let’s see the arithmetic operators in action in an example.



     
     
    >>> More Practices Articles          >>> More By Apress Publishing
     

       

    PRACTICES ARTICLES

    - More Techniques for Finding Things
    - Finding Things
    - Finishing the System`s Outlines
    - The System in So Many Words
    - Basic Data Types and Calculations
    - What`s the Address? Pointers
    - Design with ArgoUML
    - Pragmatic Guidelines: Diagrams That Work
    - Five-Step UML: OOAD for Short Attention Span...
    - Five-Step UML: OOAD for Short Attention Span...
    - Introducing UML: Object-Oriented Analysis an...
    - Class and Object Diagrams
    - Class Relationships
    - Classes
    - Basic Ideas





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek