Task: Read a temperature and convert between Celsius and Fahrenheit using the correct formulas: F = C × 9/5 + 32 and C = (F − 32) × 5/9. Print neatly to two decimal places.
/*
Program: Temperature Converter (U1)
What it does:
- Asks the user which input scale they have (C for Celsius, F for Fahrenheit).
- Reads the temperature value and converts to the other scale.
- Prints the result to two decimal places.
Formulas:
- Fahrenheit from Celsius: F = C * 9/5 + 32
- Celsius from Fahrenheit: C = (F - 32) * 5/9
*/
#include <stdio.h>
#include <ctype.h> /* for toupper() */
int main(void) {
char scale;
double temp, c, f;
printf("Enter input scale (C for Celsius, F for Fahrenheit): ");
if (scanf(" %c", &scale) != 1) {
printf("Invalid input for scale.\n");
return 0;
}
printf("Enter temperature: ");
if (scanf("%lf", &temp) != 1) {
printf("Invalid temperature.\n");
return 0;
}
scale = toupper((unsigned char)scale);
if (scale == 'C') {
f = temp * 9.0 / 5.0 + 32.0;
printf("%.2f C = %.2f F\n", temp, f);
} else if (scale == 'F') {
c = (temp - 32.0) * 5.0 / 9.0;
printf("%.2f F = %.2f C\n", temp, c);
} else {
printf("Unknown scale '%c'. Use C or F.\n", scale);
}
/* Example:
Input: scale=C, temp=37 -> 37.00 C = 98.60 F
Input: scale=F, temp=98.6 -> 98.60 F = 37.00 C
*/
return 0;
}