digression. apparently I needed to prove to myself that I could implement Celsius <-> Fahrenheit conversion in C. derp.
parent
18376aa6e4
commit
2e4c431f0d
@ -0,0 +1,47 @@
|
||||
#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 die_usage(const char *msg) {
|
||||
printf("Usage: temperatures [FC]<temp>\n");
|
||||
printf("%s\n", msg);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char * argv[]) {
|
||||
if (argc < 2) {
|
||||
die_usage("");
|
||||
}
|
||||
|
||||
char msg[255];
|
||||
double temp;
|
||||
const char * temp_string = argv[1];
|
||||
|
||||
size_t temp_len = strlen(temp_string);
|
||||
|
||||
if (strncmp(temp_string, "F", temp_len) > -1) {
|
||||
sscanf(temp_string, "F%lf", &temp);
|
||||
printf("%.2lf\n", f2c(temp));
|
||||
} else if (strncmp(temp_string, "C", temp_len) > -1) {
|
||||
sscanf(temp_string, "C%lf", &temp);
|
||||
printf("%.2lf\n", c2f(temp));
|
||||
} else {
|
||||
sprintf(msg, "Argument '%s' does not match '[FC]<temp>'",
|
||||
temp_string);
|
||||
die_usage(msg);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Reference in new issue