2012-04-03 04:10:27 +00:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
2012-05-28 17:13:07 +00:00
|
|
|
#include <string.h>
|
2012-04-03 04:10:27 +00:00
|
|
|
|
|
|
|
|
|
|
|
double c2f(double celsius) {
|
|
|
|
return ((9.0 / 5.0) * celsius) + 32.0;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
double f2c(double fahrenheit) {
|
|
|
|
return (5.0 / 9.0) * (fahrenheit - 32.0);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2012-05-28 17:13:07 +00:00
|
|
|
int usage(const char *msg) {
|
2012-05-07 03:31:45 +00:00
|
|
|
printf("Usage: temperatures <temp>[fFcC]\n");
|
2012-05-28 17:13:07 +00:00
|
|
|
if (msg != NULL) {
|
|
|
|
printf("%s\n", msg);
|
|
|
|
}
|
|
|
|
return 1;
|
2012-04-03 04:10:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
int main(int argc, char * argv[]) {
|
|
|
|
if (argc < 2) {
|
2012-05-28 17:13:07 +00:00
|
|
|
usage(NULL);
|
|
|
|
return 2;
|
2012-04-03 04:10:27 +00:00
|
|
|
}
|
|
|
|
|
2012-05-28 17:13:07 +00:00
|
|
|
int ret;
|
2012-04-03 04:10:27 +00:00
|
|
|
char msg[255];
|
|
|
|
double temp;
|
2012-05-07 03:31:45 +00:00
|
|
|
char scale = '\0';
|
2012-05-28 17:13:07 +00:00
|
|
|
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-04-03 04:10:27 +00:00
|
|
|
|
2012-05-07 03:31:45 +00:00
|
|
|
switch (scale) {
|
|
|
|
case 'c':
|
|
|
|
case 'C':
|
2012-05-28 17:13:07 +00:00
|
|
|
printf(out_fmt, c2f(temp), 'F');
|
2012-05-07 03:31:45 +00:00
|
|
|
break;
|
|
|
|
case 'f':
|
|
|
|
case 'F':
|
2012-05-28 17:13:07 +00:00
|
|
|
printf(out_fmt, f2c(temp), 'C');
|
2012-05-07 03:31:45 +00:00
|
|
|
break;
|
|
|
|
default:
|
2012-05-28 17:13:07 +00:00
|
|
|
sprintf(msg, "Unknown scale: '%c'", scale);
|
|
|
|
usage(msg);
|
2012-05-07 03:31:45 +00:00
|
|
|
break;
|
2012-04-03 04:10:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|