C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Handling Ints and Floats

By David Bolton, About.com

4 of 8

Learn about Arithmetic Operations

Writing computer software wouldn't be much use if you couldn't do addition, subtraction etc. Here's example 2.
// ex2numbers.cpp
//
#include <iostream>

using namespace std;

int main()
{
int a=9;
int b= 12;
int total=a+b;
cout << "The total is " << total << endl;

return 0;
}

Explanation of Example 2

Three int variables are declared. A and B are assigned values, then total is assigned the sum of A and B.

Before running this example

Here's a little tip to save time when running Command Line applications.

When you run this program from the Command Line, it should output "The number is 22".

Other Arithmetic Operations

As well as addition, you can do subtraction, multiplication and division. Just use + for addition, - for subtraction, * for multiplication and / for division.

Try changing the above program- use subtraction or multiplication. You can also change ints to floats or doubles.

With floats you have no control over how many decimal points are displayed unless you set the precision as shown earlier.

On the next page : Learn about output formats.

Explore C / C++ / C#

About.com Special Features

C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Some Arithmetic Operations

©2009 About.com, a part of The New York Times Company.

All rights reserved.