/* Plot2.cpp Revised version of Plot1.cpp. Bruce M. Bolden October 23, 2006 * --------------------------------------------------- */ #include #include #include #include #include using namespace std; // Prototypes void PlotLine( ofstream& fOut ); void Plot( ofstream& fOut, double x, double y, double yMin, double yMax ); int main() { ofstream fOut( "plot1.out", ios::out ) ; if( !fOut ) { cout << "Unable to open: \"plot1.out\"" << endl; exit( -1 ); } PlotLine( fOut ); // draw a simple line fOut.close(); return 0; } /* PlotLine * * Display the plot of a line. */ void PlotLine( ofstream& fOut ) { double xMin = -2.0; // range variables double xMax = 2.0; double xStep = 0.5; double yMin = -2.0; // plot scale double yMax = 3.0; double x, y; fOut << " Plot of y = x + 1\n" << endl; for( x = xMin ; x <= xMax ; x += xStep ) { y = 1.0 * x + 1.0; Plot( fOut, x, y, yMin, yMax ); } } /* Plot * * Display a value (y) if it lies between the minimum and maximum * values (yMin and yMax). * Output is written to the output stream referred to by fOut. */ void Plot( ofstream& fOut, double x, double y, double yMin, double yMax ) { const int bShowNumbers = 1; // show numbers on plot const int MAX_LINE = 60; // total line length ~80 chars const int OFFSET = 20; // offset from beginning of line const int DEC_PLACES = 3; // number of decimal places const char AXIS_SYMBOL = '|'; const char PLOT_SYMBOL = '*'; char line[MAX_LINE+1]; int index; // location of "point" in line // clear line for( int i = 0 ; i < MAX_LINE ; i++ ) line[i] = ' '; line[MAX_LINE] = '\0'; // "seal off" line // x-axis index = (int)(MAX_LINE * ((0.0-yMin)/(yMax-yMin))); if( index >= 0 && index < MAX_LINE ) { line[index] = AXIS_SYMBOL; } // scale and "plot" data point index = (int)(MAX_LINE * ((y-yMin)/(yMax-yMin))); //cout << index << endl; // testing aid if( index >= 0 && index < MAX_LINE ) { line[index] = PLOT_SYMBOL; } // output if( !bShowNumbers ) { fOut << setw(OFFSET); // this is unreachable } else { fOut.setf( ios::fixed ); fOut << setw(OFFSET/2) << setprecision(DEC_PLACES) << x; fOut << setw(OFFSET/2) << setprecision(DEC_PLACES) << y; } fOut << " | "; fOut << line << endl; // plot "line" }