Last Updated on 2021-05-06 by Clay
In programming, there are so-called arithmetic operators, such as addition (+), subtraction (-), multiplication (*) and division (/). In addition, the commonly used operator include the % symbol for calculating the remainder.
Through these different operators, we can let the computer help us perform calculations and handle all kinds of tasks.
Arithmetic Expression
Addition (+)
#include <iostream> using namespace std; int main() { cout << 1+2 << endl; return 0; }
Output:
3
subtraction (-)
#include <iostream> using namespace std; int main() { cout << 7 - 5 << endl; return 0; }
Output:
2
multiplication (*)
#include <iostream> using namespace std; int main() { cout << 7 * 5 << endl; return 0; }
Output:
35
division (/)
#include <iostream> using namespace std; int main() { cout << 7 / 5 << endl; return 0; }
Output:
1
There is only division's answer is not the same as in our ordinary lives. This is because the number we use is an integer (data-type is int), so the answer returned by the calculation can only be a integer.
If you want to see more accurate results of calculating decimals, we can convert 7 and 5 to float or double for calculation.
#include <iostream> using namespace std; int main() { cout << (float)7 / (float)5 << endl; return 0; }
Output:
1.4
Remainder (%)
This is a rare calculation in daily life, which can help us find the remainder after dividing a value. For example, if 7 is divided by 5, the remainder is 2, we can use the operator to calculate.
#include <iostream> using namespace std; int main() { cout << 7 % 5 << endl; return 0; }
Output:
2
Strings can also be added
It is worth mentioning that strings can actually be added together.
#include <iostream> #include <string> using namespace std; int main() { string str_01 = "Today is a "; string str_02 = "nice day."; cout << str_01 + str_02 << endl; return 0; }
Output:
Today is a nice day.
References
Read More
- [Linux][C++] How to compile and execute a C++ program
- [C++] Tutorial(1): Data Type
- [C++] Tutorial(2): Arithmetic Expression
- [C++] Tutorial(3): Data Input and Output
- [C++] Tutorial(4): if-else, switch, loop and flow control
- [C++] Tutorial(5): File Read and Write
- [C++] Tutorial(6): Pointer and Reference
- [C++] Tutorial(7): Functions