Shortcut operators
Changing a variable using its own value is so common that C++ has shortcuts:
| Shortcut | Same as |
|---|---|
x += 5; | x = x + 5; |
x -= 2; | x = x - 2; |
x *= 3; | x = x * 3; |
x /= 2; | x = x / 2; |
x++; | x = x + 1; |
x--; | x = x - 1; |
#include <iostream>
using namespace std;
int main() {
int coins = 10;
coins += 5;
cout << coins << "\n";
coins *= 2;
cout << coins << "\n";
coins++;
cout << coins << "\n";
coins--;
coins--;
cout << coins << "\n";
return 0;
}Output
15 30 31 29
Tip: Now you know where the name C++ comes from:
C++means “C, increased by one”.
Converting types: static_cast
Sometimes you have two ints but want a decimal answer, like an average. static_cast<double>(x) turns x into a double for that calculation:
#include <iostream>
using namespace std;
int main() {
int total = 17;
int count = 4;
cout << total / count << "\n"; // int division: 4
cout << static_cast<double>(total) / count << "\n"; // 4.25
double price = 9.99;
int rounded = static_cast<int>(price); // cuts off .99
cout << rounded << "\n";
return 0;
}Output
4 4.25 9
Maths functions: <cmath>
Add #include <cmath> to get ready-made maths functions:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
cout << sqrt(81) << "\n"; // square root
cout << pow(2, 10) << "\n"; // 2 to the power of 10
cout << abs(-7) << "\n"; // distance from zero
cout << round(4.6) << "\n"; // nearest whole number
cout << floor(4.6) << "\n"; // round down
cout << ceil(4.1) << "\n"; // round up
return 0;
}Output
9 1024 7 5 4 5
Controlling decimal places
To always show, say, 2 decimal places (great for money), use fixed and setprecision from <iomanip>:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double price = 7.5;
cout << fixed << setprecision(2);
cout << "Price: $" << price << "\n";
cout << "Tax: $" << price * 0.08 << "\n";
return 0;
}Output
Price: $7.50 Tax: $0.60