Tom Kelliher, CS18
Mar. 11, 1996
Schedule for middle third of class.
Example: complex numbers
Form:
Formulas for:
New type definitions:
typedef struct cmplx { double real; double imag; } complex; // new type is complex typedef struct plr { double r; double theta; } polar; // new type is polar
/********************************************************************** * convert --- convert the complex number c to polar form * needs math.h **********************************************************************/ polar convert(complex c) { polar p; p.r = sqrt( c.real * c.real + c.imag * c.imag); if (c.real < EPSILON) // too close to zero to permit division { if (c.imag < EPSILON) p.theta = 0.0; else if (c.imag > 0.0) p.theta = PI / 2.0; else p.theta = 3.0 * PI / 2.0; } // Note: atan() returns a result in [-PI/2, PI/2], affecting the // theta computations for quadrants 2, 3, and 4. else if (c.real > 0.0 && c.imag >= 0.0) // point in quadrant 1 p.theta = atan(c.imag / c.real); else if (c.real < 0.0) // point in quadrants 2 or 3 p.theta = PI - atan(c.imag / c.real); else // point in quadrant 4 p.theta = 2 * PI + atan(c.imag / c.real); return p; }
Used to name a new type or rename an old type:
typedef double doubleArray10[10]; doubleArray10 data; for (int i = 0; i < 10; ++i) data[i] = 0.0;
typedef struct rat { int num; int den; } rational; rational a = { 1, 3 };
typedef int integer; typedef int signedInteger; integer i; signedInteger j;
Syntax:
typedef <TypeSpecifier> <Synonym>;
Collection of related symbolic constants.
Example: Path finding in a maze
2-D array representation of a maze:
enum MazeStates { WALL; HALL; PATH; DEADEND; GOAL; }; enum MazeStates maze[MAZE_HEIGHT][MAZE_WIDTH]; maze[0][0] = GOAL; if (maze[i][j] == DEADEND) ; maze[i][j] = 0; // ok; not a good idea, though int i = HALL // ok; integral promotion
Typical boolean example:
enum Boolean { FALSE = 0; TRUE = 1; } Boolean success; ... if (success == TRUE) ;
For the example program involving the complex type, finish the program so that it compiles and correctly runs.