Data Types
Every variable has a type. The type decides what kind of value the variable can hold. These five types are enough for a long time:
| Type | Holds | Example |
|---|---|---|
int | whole numbers | 4, -12, 0 |
double | numbers with a decimal | 9.99, -0.5 |
char | one character, in ' ' | 'B', '?' |
bool | true or false | true |
string | text, in " " | "Paris" |
#include <iostream>
#include <string>
using namespace std;
int main() {
int wheels = 4;
double price = 9.99;
char grade = 'B';
bool open = true;
string city = "Paris";
cout << wheels << "\n";
cout << price << "\n";
cout << grade << "\n";
cout << open << "\n";
cout << city << "\n";
return 0;
}
Output:
4
9.99
B
1
Paris
To use string, add #include <string> at the top of the program.
Look at the fourth line of the output. cout prints true as 1, and false as 0. Remember this when you print a bool.
Also look at the quotes. Single quotes make a char, which is exactly one character. Double quotes make a string. So 'B' and "B" are different types.
How cout prints decimals
By default, cout shows a double with at most 6 significant digits, that is, 6 digits counted from the first digit that is not zero:
double pi = 3.14159265;
double big = 1234567.89;
double whole = 2.0;
cout << pi << "\n";
cout << big << "\n";
cout << whole << "\n";
Output:
3.14159
1.23457e+06
2
pi was rounded to 6 digits. big has 7 digits before the decimal point, more than 6, so cout rounded it and switched to a short form: 1.23457e+06 means "1.23457 times 1,000,000". And 2.0 printed as just 2.
To choose the number of decimal places yourself, use fixed and setprecision. They come from the <iomanip> library, so add #include <iomanip>:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double big = 1234567.89;
double whole = 2.0;
cout << fixed << setprecision(2);
cout << big << "\n";
cout << whole << "\n";
return 0;
}
Output:
1234567.89
2.00
fixed << setprecision(2) means "always show exactly 2 digits after the decimal point". You write it once, and it stays on for every double that cout prints after it. This is the usual way to print prices and averages.
Let the compiler pick the type with auto
If you write auto instead of a type, the compiler picks the type from the starting value:
auto count = 5;
auto ratio = 2.5;
cout << count << " " << ratio << "\n";
Output:
5 2.5
count became an int, and ratio became a double. Because the type comes from the value, auto always needs a starting value. In this course, we still write the type when it is short, like int, so you can see it. auto helps most with long type names, which you will meet later.
In the exercise, five variables are missing their types. Fill them in.