Skip to content

Instantly share code, notes, and snippets.

@shelling
Created September 28, 2009 07:46
Show Gist options
  • Select an option

  • Save shelling/195256 to your computer and use it in GitHub Desktop.

Select an option

Save shelling/195256 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdarg.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
//
// Please compile with this arg -std=c99 when using GCC 4.x.
// commenting with double slash and inline function are C99's feature
//
// function prototype
static inline double temperature(double);
static inline double Celsius2Fahrenheit( double celsius );
static inline double Fahrenheit2Celsius( double fahrenheit );
static inline double Average( int portion, ... );
static inline double AverageTemperature( double time );
// main function
int main( void ) {
FILE *input = fopen( "input.dat", "r" );
if ( input == NULL ) {
printf( "Input file could not be opened. Interupt program now.\n" );
raise( SIGINT );
}
rewind( input ); // move file point back to head of file
char line[ 5 ];
fgets( line, 5, input );
char *tokenPtr;
tokenPtr = strtok( line, " " ); double hr = atof( tokenPtr );
tokenPtr = strtok( NULL, " " ); double min = atof( tokenPtr );
double time = hr + min / 60; printf( "time is %.2f hours\n", time );
double celsius = AverageTemperature( time );
double fahrenheit = Celsius2Fahrenheit( celsius );
printf( "average is %.2fºC or %.2fºF\n", celsius, fahrenheit );
FILE *output = fopen( "output.dat", "w" );
if ( output == NULL ) {
printf( "Output file could not be opened. Interupt program now.\n" );
raise( SIGINT );
}
fprintf( output, "%f%s", fahrenheit, "ºF" );
return 0;
}
// implementation
static inline double temperature( double t ) {
return ( 4 * t * t * t ) / ( t + 2 ) - 20;
}
static inline double Celsius2Fahrenheit( double celsius ) {
return ( 9.L * celsius / 5.L ) + 32.L;
}
static inline double Fahrenheit2Celsius( double fahrenheit ) {
return ( 5.L / 9.L ) * ( fahrenheit - 32.L );
}
// ... is a macro defined in stdarg.h for receiving variable arguments
static inline double Average( int portion, ... ) {
double total = 0;
va_list ap;
va_start( ap, portion );
for( int i = 1 ; i <= portion ; i++ ) {
total += va_arg( ap, double );
}
va_end( ap );
return total / portion;
}
static inline double AverageTemperature( double time ) {
double segment = time / 5.L;
return Average(
6,
temperature( 0 ),
temperature( segment ),
temperature( segment * 2 ),
temperature( segment * 3 ),
temperature( segment * 4 ),
temperature( time )
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment