Here’s an example of a temperature conversion program in C that converts between Celsius and Fahrenheit:
#include <stdio.h>
float convertCelsiusToFahrenheit(float celsius) {
return (celsius * 9/5) + 32;
}
float convertFahrenheitToCelsius(float fahrenheit) {
return (fahrenheit - 32) * 5/9;
}
int main() {
float temperature;
int choice;
// Prompt the user to enter the temperature
printf("Enter the temperature: ");
scanf("%f", &temperature);
// Prompt the user to select the conversion type
printf("Select conversion:\n");
printf("1. Celsius to Fahrenheit\n");
printf("2. Fahrenheit to Celsius\n");
printf("Enter your choice: ");
scanf("%d", &choice);
// Perform the conversion based on user choice
switch(choice) {
case 1:
printf("%.2f degrees Celsius is equal to %.2f degrees Fahrenheit.\n", temperature, convertCelsiusToFahrenheit(temperature));
break;
case 2:
printf("%.2f degrees Fahrenheit is equal to %.2f degrees Celsius.\n", temperature, convertFahrenheitToCelsius(temperature));
break;
default:
printf("Invalid choice. Please try again.\n");
break;
}
return 0;
}
To compile and run the program, follow these steps:
- Save the code in a file with a
.c
extension, such astemperature_conversion.c
. - Open a terminal or command prompt and navigate to the directory where the file is saved.
- Compile the program using a C compiler (e.g., GCC) by running the following command:
gcc -o temperature_conversion temperature_conversion.c
This will create an executable file namedtemperature_conversion
. - Run the program by executing the following command:
./temperature_conversion
The program prompts the user to enter a temperature value and then asks for the conversion type: either Celsius to Fahrenheit or Fahrenheit to Celsius. Based on the user’s choice, the program performs the appropriate conversion and displays the converted value on the screen.
Feel free to modify and enhance the program as per your specific requirements.