The math operators in C++ are as follows:
| C++ Code | Meaning |
| + | addition |
| - | subtraction |
| * | multiplication |
| / | division |
| % | modulus or remainder |
The first four of the math operators work in the same way you learned to do math as a child. You can use them with variables or with actual numbers (these are called constants. For example the number 8 always has one value and only one value. Its value is conatant. A variables is assigned and latter can be reassigned. Its value can change, i.e. it is variable.)
cout << 4*4; //display the product of 4 times 4
It is probably most useful to use math operators with variables whose values come from user input. In the following program we will get a number from the user, do a calculation with it and print the result to the screen.
#include <iostream>
using namespace std;
int main()
{
int ht, wt, ft, in;
cout << "\nThis program calculates your ideal weight.\n"
<< "Please enter your height in inches: ";
cin >> ht;
ft = ht/12;
in = ht % 12; //find the remainder of ht divided by 12
wt = ht/2.3;
cout << "You are " << ft << " feet, " << in << " inches tall";
cout << "\nYour ideal weight is " << wt << ". \n";
cin.get(); //cin.get(); waits for to be pressed.
cin.get(); // Use cin.get() to keep the program running.
return 0;
}
In the program abve there are comments that are ignored by the compiler. It serves as documentation that clarifies what the program is doing. The line in = ht%12; //find the remainder of ht divided by 12, the two slash marks tell the compiler to ignore the rest of the line.
The modulus operator % only lets us find the remainder of one number divided by another. The expression 125 % 12 will yield an answer of 5.
ASSIGNMENT #1
Lesson: IO, variables, and Math
operators
Due Date: February 5
1.Write a program that takes a persons
weight (use cin operator and an int variable) and prints the persons weight on
the Moon (another int variable) to the screen. Use appropriate cout statements.
Moon weight is one sixth of Earth weight.
2.Write a program that takes an
integer and and gives the square and cube of that integer. Add proper cout
statements to explain all values.
Compile and test your programs.