Created
September 21, 2015 01:05
-
-
Save Rhomboid/2e2146247b3bb4a3ddf2 to your computer and use it in GitHub Desktop.
Units conversion example in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdarg.h> | |
struct conversion { | |
const char *from, *to; | |
double scale, offset; | |
} conversions[] = { | |
{ "Celsius", "Fahrenheit", 9./5, 32 }, | |
{ "Fahrenheit", "Celsius", 5./9, -32 * 5./9 }, | |
{ "Kilometers", "Miles", 1/1.609344, 0 }, | |
{ "Miles", "Kilometers", 1.609344, 0 }, | |
{ "Kilograms", "Pounds", 1/0.45359237, 0 }, | |
{ "Pounds", "Kilograms", 0.45359237, 0 } | |
}; | |
void checked_scanf(const char *fmt, ...) | |
{ | |
va_list varargs; | |
va_start(varargs, fmt); | |
for(char line[256]; fgets(line, sizeof(line), stdin); ) { | |
if(vsscanf(line, fmt, varargs) == 1) { | |
return; | |
} | |
puts("Invalid input, try again."); | |
} | |
puts("EOF encountered without valid input, giving up."); | |
exit(1); | |
} | |
int main(void) | |
{ | |
const int num_conversions = sizeof(conversions) / sizeof(conversions[0]); | |
for(;;) { | |
puts("What would you like to convert?"); | |
for(int i = 0; i < num_conversions; i++) { | |
printf("%d. %s to %s\n", i + 1, conversions[i].from, conversions[i].to); | |
} | |
int choice; | |
for(;;) { | |
checked_scanf("%d", &choice); | |
if(choice >= 1 && choice <= num_conversions) { | |
--choice; | |
break; | |
} | |
puts("Invalid choice, try again."); | |
} | |
double low, high, step; | |
printf("Please enter a lower limit: "); | |
checked_scanf("%lf", &low); | |
printf("Please enter an upper limit: "); | |
checked_scanf("%lf", &high); | |
printf("Please enter the increment value: "); | |
checked_scanf("%lf", &step); | |
printf("\n%10s %10s\n---------- ----------\n", conversions[choice].from, conversions[choice].to); | |
for(double val = low; val <= high; val += step) { | |
double converted = val * conversions[choice].scale + conversions[choice].offset; | |
printf("%10.2f %10.2f\n", val, converted); | |
} | |
puts("\nWould you like to convert something else? y/n"); | |
char quit[2]; | |
checked_scanf("%1[yYnN]", &quit); | |
if(quit[0] == 'n' || quit[0] == 'N') break; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment