Transcript Expressions

Engineering 1020
Introduction to Programming
Peter King
[email protected]
www.engr.mun.ca/~peter
Winter 2010
ENGI 1020: Expressions
•
C++ handles expressions as either:
–
–
•
Integer (or long)
Real (double, float)
So what happens here?
double y = 2 * 5.6;
•
2 is an integer, 5 is real, y is a double
ENGI 1020: Expressions
double y = 2 * 5.6;
–
–
–
–
C++ makes a decision on the fly
2 is converted to 2.0
double multiplication is used
y gets a double value
y = 11.2
ENGI 1020: Expressions
•
C++ will tend to convert int to double
– Double are more precise
int pi = 3;
double pi = 3.1459 .......;
–
•
We can convert an int to double without losing any
information
How can a programmer take control of this?
Maybe I want to convert a double to an int
ENGI 1020: Expressions
•
Explicit Casting
–
•
Fancy talk for 'forcing the type conversion'
2 types
–
Type cast
double x = 3.1;
int y = 2 * (int) x;
–
Implied cast
int tripler (double y){
return 3 * y;
}
ENGI 1020: Expressions
•
What happens to a double converted to an int?
–
–
It is NOT rounded
The decimal part is simple cut off (truncated)
•
•
•
A compiler will probably warn you about this
–
•
3.14 → 3
5.999999 → 5
Not an error, just a warning
Some Examples
ENGI 1020: Expressions
•
Composite Assignment operators
–
Shorthand for common operation
–
–
–
–
x = x + 2 → x += 2
y = y / 9 → y /= 9
z = z – 1 → z -= 1
MinTemp = minTemp * 1.2 → minTemp *= 1.2
ENGI 1020: Expressions
•
Order of operations
–
Highest
•
•
•
Stuff in parenthesis ()
Unary operators
Binary operators
–
–
–
•
Lowest
Examples
*, /, % (from left to right)
+, - (from left to right)