/* ------------------------------------------------------------------- // Figure 15.9: Writing a file of voltages. // ------------------------------------------------------------------- */ #include "tools.h" #define V 10 /* battery voltage */ #define TAU 0.15 /* time constant for this circuit (s) */ #define step (1.0 / 15.0) /* time step for lines of table */ #define epsilon (step / 2.0) /* for floating comparison to end loop */ double f( double t ) { return V * (1 - exp( -t / TAU )); } void main( void ) { double t; /* time since switch closed */ double v; /* voltage at time t */ char table; /* 'y' for table, else coordinate format */ string format = "(%.2f, %.2f)\n"; /* format for coordinate output */ stream myfile = fopen( "voltage.dat", "w" ); if (myfile == NULL) fatal( "Cannot open voltage.dat" ); printf( "\n Write output in table form (y/n)? " ); scanf( " %c", &table ); if (tolower( table ) == 'y') { fprintf( myfile, " time voltage \n\n" ); /* table headings */ format = "%8.2f %14.2f\n"; } printf( "\n Writing table to file voltage.dat\n" ); for (t = 0.0; t <= (1.0 + epsilon); t += step ) { v = f( t ); fprintf( myfile, format, t, v ); } fclose( myfile ); bye(); }