Calculations with Integers - C++ Data Type

C++ examples for Data Type:int

Introduction

Basic Arithmetic Operations

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

op= Assignment Operators

Operation Operator Operation Operator
Addition += Bitwise AND &=
Subtraction -= Bitwise OR |=
Multiplication *= Bitwise exclusive OR^=
Division /= Shift left <<=
Modulus%= Shift right >>=

The following code converts distances that you enter from the keyboard and in the process illustrates using the arithmetic operators:

Demo Code

#include <iostream>

int main()/*  w  w w.j  a v a2s.c  o m*/
{
  unsigned int yards {}, feet {}, inches {};

  std::cout << "Enter a distance as yards, feet, and inches "
            << "with the three values separated by spaces:"
            << std::endl;
  std::cin >> yards >> feet >> inches;

  const unsigned int feet_per_yard {3U};
  const unsigned int inches_per_foot {12U};

  unsigned int total_inches {};

  total_inches = inches + inches_per_foot*(yards*feet_per_yard + feet);

  std::cout << "The distances corresponds to " << total_inches << " inches.\n";

  std::cout << "Enter a distance in inches: ";
  std::cin >> total_inches;

  feet = total_inches/inches_per_foot;
  inches = total_inches%inches_per_foot;

  yards = feet/feet_per_yard;

  feet = feet%feet_per_yard;

  std::cout << "The distances corresponds to "
            << yards  << " yards "
            << feet   << " feet "
            << inches << " inches." << std::endl;
}

Result


Related Tutorials