box-o-sand/digressions/temperatures.c

72 lines
1.4 KiB
C
Raw Normal View History

#include <stdio.h>
#include <stdlib.h>
#include <string.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 usage(const char *msg) {
2012-05-07 03:31:45 +00:00
printf("Usage: temperatures <temp>[fFcC]\n");
if (msg != NULL) {
printf("%s\n", msg);
}
return 1;
}
int main(int argc, char * argv[]) {
if (argc < 2) {
usage(NULL);
return 2;
}
int ret;
char msg[255];
double temp;
2012-05-07 03:31:45 +00:00
char scale = '\0';
const char *in_fmt = "%lf%c";
const char *out_fmt = "%.2lf%c\n";
if (((int)strlen(argv[1]) == 1) && (argv[1][0] == '-')) {
ret = fscanf(stdin, in_fmt, &temp, &scale);
} else {
const char * temp_string = argv[1];
ret = sscanf(temp_string, in_fmt, &temp, &scale);
}
if ((ret == 0) || (ret == EOF)) {
usage("No temperature provided!");
return 1;
}
if (ret == 1) {
usage("No scale provided!");
return 1;
}
2012-05-07 03:31:45 +00:00
switch (scale) {
case 'c':
case 'C':
printf(out_fmt, c2f(temp), 'F');
2012-05-07 03:31:45 +00:00
break;
case 'f':
case 'F':
printf(out_fmt, f2c(temp), 'C');
2012-05-07 03:31:45 +00:00
break;
default:
sprintf(msg, "Unknown scale: '%c'", scale);
usage(msg);
2012-05-07 03:31:45 +00:00
break;
}
return 0;
}