Tom Kelliher, CS17
Feb. 28, 1996
int change; int quarters; int dimes; int nickels; int pennies; cout << "Amount of change to be given: "; cin >> change; cout << "Making change for " << change << " cents.\n"; quarters = change / 25; change %= 25; dimes = change / 10; change %= 10; nickels = change / 5; change %= 5; pennies = change; cout << "\nChange:\n"; cout << "Quarters: " << quarters << endl; cout << "Dimes: " << dimes << endl; cout << "Nickels: " << nickels << endl; cout << "Pennies: " << pennies << endl;
We know the types of:
9 / 5 9.0 / 5What about:
int a = 5, b = 7, c = 11; double x = 1.0, y = 9.0, z = 13.0; a = b + c + x - a; x = (a + c) / b; a = (x + b) / c;
We must determine:
The rules (for what we've learned):
Remember:
a = (b + c) / x;has three (sub-)expressions.
What are the types, order of evaluation, value?
Consider:
x = (a = (b + c) / x) + 5;What are the types, order of evaluation, value?
Is this the same?
x = a = (b + c) / x + 5;
Type conversion
x = 5 / 9; // can be fixed: 5.0 / 9.0 a = 5; b = 9; x = a / b; // can this be fixed? x = (double) a / (double) b; // yes!
Unary operator --- same precedence as ++
Forced integer operations:
a = (int) x / (int) y; a = (int) x / y; // integer division?
C++'s core is missing I/O --- included in iostream library
It's also missing math functions --- found in math library
Mathematically, what is a function?
``Silly'' example:
int add(int a, int b) { return a + b; } int i, j, k, l; i = j + k; // same result i = add(j, k); i = j + k + l; // same result i = add(add(j, k), l);
Properties:
In using library functions, explicitly cast arguments
Examples:
x = sqrt(y); x = sqrt(a); // design/syntax error x = sqrt((double) a); // fixed a = sqrt((double) b); // implicit cast in assignment x = pow(y, 3.0); // x is assigned y cubed
Function call --- () --- is a primary operator, highest precedence seen so far:
<<
, >>
(left)
x = pow(y, 2); // slow x = y * y; // much faster
++a; // ok a = ++b - c--; // huh???
Using the math library, write a program to compute the length of the
hypotenuse of a right triangle. The inputs to your program will be the
lengths of the other two sides. Assume that all quantities are of type
double.