2.x — Chapter 2 summary and quiz
Quick review#
- A type decides what a value is and how much memory it uses.
intfor whole numbers,doublefor decimals,boolfor true/false,charfor one character,std::stringfor text.'A'is achar."A"is a string.- Numbers can overflow if they get too big for their type.
- Decimals are not exact. Don't compare them with
==. constandconstexprmake values that cannot change.static_cast<type>(value)changes a type on purpose.
Pick an answer. You find out right away if it is right.
Which type is best for storing a price like 4.99?
double holds numbers with a decimal point. int would throw the .99 away.
What's the difference between 'A' and "A"?
Single quotes = one character. Double quotes = text.
What happens here? const int lives { 3 }; lives = 4;
A const variable can never be changed after it's made. The compiler stops you.
Which type would you use for each?
- The number of students in a class
- The price of a book
- Whether a door is locked
- A person's name
- A grade from A to F
intdoubleboolstd::stringchar
What is wrong here?
char answer { "y" };"y" uses double quotes, so it is text (a string), not a char. Use single quotes: char answer { 'y' };
This prints 2. How do you make it print 2.5?
int total { 5 };int count { 2 };std::cout << total / count;Convert one of them to double first:
std::cout << static_cast<double>(total) / count;Write a program that asks for a temperature in Celsius (it may have decimals) and prints it in Fahrenheit. The formula is F = C × 9 / 5 + 32.
#include <iostream> int main(){ std::cout << "Temperature in Celsius: "; double celsius {}; std::cin >> celsius; double fahrenheit { celsius * 9.0 / 5.0 + 32.0 }; std::cout << celsius << " C is " << fahrenheit << " F\n"; return 0;}Note the .0 on the numbers so the math uses decimals.
Tip: press ← / → to move between lessons, / to search.