More Math
- When multiple types are involved in a computation
- 3 + 2.98 will become a float even if 3 is an int
- The compiler will convert between types.
- This is called type coercion or just coercion
- When we do it, it is called type conversion
- In general it is better if we control things.
- Type conversion
- There are multiple ways to do this.
- You will assume
float data
- You will rarely see
(int) data
- You will frequently see
int(data)
- You should probably use
static_cast<int>(data)
- You can cast from any type to most other types.
- A word of caution
- Conversion and type casting doesn't always produce what you expect.
- Assume
float floatData = 4.6;
-
intData = static_cast<int>(floatData)
produces a 4.
- Conversion to integer truncates, it does not round.
- A way to round is
-
intData = static_cast<int>(floatData + 0.5)
produces a 5.
-
- Write a program that converts between Fahrenheit and Celsius
- $c = \frac{5}{9}(f-32)$
- $f = \frac{9}{5}c + 32$