box-o-sand/digressions/temperatures.c

50 lines
916 B
C
Raw Normal View History

#include <stdio.h>
#include <stdlib.h>
double c2f(double celsius) {
return ((9.0 / 5.0) * celsius) + 32.0;
}
double f2c(double fahrenheit) {
return (5.0 / 9.0) * (fahrenheit - 32.0);
}
int die_usage(const char *msg) {
2012-05-07 03:31:45 +00:00
printf("Usage: temperatures <temp>[fFcC]\n");
printf("%s\n", msg);
exit(1);
}
int main(int argc, char * argv[]) {
if (argc < 2) {
die_usage("");
}
char msg[255];
double temp;
2012-05-07 03:31:45 +00:00
char scale = '\0';
const char * temp_string = argv[1];
2012-05-07 03:31:45 +00:00
sscanf(temp_string, "%lf%c", &temp, &scale);
switch (scale) {
case 'c':
case 'C':
printf("%.2lf\n", c2f(temp));
break;
case 'f':
case 'F':
printf("%.2lf\n", f2c(temp));
break;
default:
sprintf(msg, "Unknown scale '%c'", scale);
die_usage(msg);
break;
}
return 0;
}