Quick Review
Integers are used for holding whole numbers. When using integers, keep an eye out for overflow and integer division problems.
Floating point numbers are used for holding real numbers (which can have fractional components). When using floating point numbers, keep an eye out for precision issues, rounding errors, and comparison issues.
Boolean values hold only true and false. They do not have any major issues.
Char values are integers that can be interpreted as an ASCII value. When using chars, be careful not to mix up ASCII code values and numbers, and watch for overflow and integer division problems.
Use the const keyword to declare symbolic constants instead of #define. It’s safer.
Comprehensive quiz
1) Why are symbolic constants usually a better choice than literal constants? Why are const symbolic constants usually a better choice than #defined symbolic constants?
2) Pick the appropriate data type for a variable in each of the following situations. Be as specific as possible. If the answer is an integer, pick a specific integer type (eg. short) based on range. If the variable should be unsigned or const, say so.
a) The age of the user (in years)
b) Whether the user wants color or not
c) pi (3.14159265)
d) The number of pages in a textbook
e) The price of a stock in dollars (to 2 decimal places)
f) How many times you’ve blinked since you were born (note: answer is in the millions)
g) A user selecting an option from a menu by letter
h) The year someone was born
3) Declare each of the above using Caste Hungarian Notation. Pick a good variable name. Don’t forget to assign values to any const variables.
4) Write the following program: The user is asked to enter 2 floating point numbers (use doubles). The user is then asked to enter one of the following mathematical symbols: +, -, *, or /. The program computes the answer on the two numbers the user entered and prints the results. If the user enters an invalid symbol, the program should print nothing.
Example of program:
Enter a value: 7
Enter a second value: 5
Enter one of the following: +, -, *, or /: *
7 * 5 is 35
Hint: You can check if the user has entered a plus symbol using an if statement (briefly covered in section 2.6) and the equality operator (used to compare two values for equality): if (chUserInput == '+') // fill in rest of code here
Solutions
0 comments: