f5902e699f
before moving on to something more fun.
69 lines
1.4 KiB
C
69 lines
1.4 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <libgen.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);
|
|
}
|
|
|
|
|
|
void die_usage(const char *prog, const char *msg) {
|
|
fprintf(stderr, "Usage: %s <temp>[FC]\n", prog);
|
|
if (msg != NULL) {
|
|
fprintf(stderr, "%s\n", msg);
|
|
}
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
|
|
int main(int argc, char * argv[]) {
|
|
const char * prog = basename(argv[0]);
|
|
int ret;
|
|
char msg[255];
|
|
double temp;
|
|
char scale = '\0';
|
|
const char *in_fmt = "%lf%c";
|
|
const char *out_fmt = "%.2lf%c\n";
|
|
const char *temp_string;
|
|
|
|
if (argc < 2) {
|
|
die_usage(prog, NULL);
|
|
}
|
|
|
|
if (((int)strlen(argv[1]) == 1) && (argv[1][0] == '-')) {
|
|
ret = fscanf(stdin, in_fmt, &temp, &scale);
|
|
} else {
|
|
temp_string = argv[1];
|
|
ret = sscanf(temp_string, in_fmt, &temp, &scale);
|
|
}
|
|
|
|
if ((ret == 0) || (ret == EOF)) {
|
|
die_usage(prog, "No temperature provided!");
|
|
}
|
|
|
|
if (ret == 1) {
|
|
die_usage(prog, "No scale provided!");
|
|
}
|
|
|
|
switch (scale) {
|
|
case 'C':
|
|
printf(out_fmt, c2f(temp), 'F');
|
|
break;
|
|
case 'F':
|
|
printf(out_fmt, f2c(temp), 'C');
|
|
break;
|
|
default:
|
|
sprintf(msg, "Unknown scale: '%c'", scale);
|
|
die_usage(prog, msg);
|
|
}
|
|
|
|
exit(EXIT_SUCCESS);
|
|
}
|