Skip to content

Instantly share code, notes, and snippets.

@robert-saramet
Last active March 21, 2024 10:15
Show Gist options
  • Select an option

  • Save robert-saramet/81fa0c2968ef4fcbfb8ee3caee573f1f to your computer and use it in GitHub Desktop.

Select an option

Save robert-saramet/81fa0c2968ef4fcbfb8ee3caee573f1f to your computer and use it in GitHub Desktop.
#include <stdio.h>
#define FREEZING_POINT_K 273.15f
#define FREEZING_POINT_F 32.0f
#define F_TO_K_RATIO (5.0f / 9.0f)
#define DEGREE_SYMBOL 248
enum Unit { Kelvin, Celsius, Fahrenheit };
float convert(float temp, enum Unit in_unit, enum Unit out_unit) {
if (in_unit == out_unit)
return temp;
if (in_unit != Kelvin) {
if (in_unit == Fahrenheit)
temp = (temp - FREEZING_POINT_F) * 5 / 9;
temp += FREEZING_POINT_K;
return convert(temp, Kelvin, out_unit);
}
temp -= FREEZING_POINT_K;
if (out_unit == Celsius)
return temp;
return temp / F_TO_K_RATIO + FREEZING_POINT_F;
}
int main(void) {
enum Unit in_unit, out_unit;
float temp;
printf("Units available:\n 0: Kelvin\n 1: Celsius\n 2: Fahrenheit\n\n");
int count = 0;
printf("Input unit [0-2]:");
count += scanf("%u", &in_unit);
printf("Output unit [0-2]:");
count += scanf("%u", &out_unit);
printf("Temperature:");
count += scanf("%f", &temp);
if (count != 3) {
fprintf(stderr, "\nError reading: invalid input");
return -1;
}
float new_temp = convert(temp, in_unit, out_unit);
printf("\nConverted temperature: %.1f", new_temp);
if (out_unit != Kelvin)
printf("%c", DEGREE_SYMBOL);
scanf("%d", &in_unit);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment