Simple C program that converts a temperature from Fahrenheit to Celsius, along with an explanation of each part of the program:
#include <stdio.h>
int main() {
// Declare variables
double fahrenheit, celsius;
// Ask the user to enter the temperature in Fahrenheit
printf("Enter the temperature in Fahrenheit: ");
scanf("%lf", &fahrenheit);
// Convert Fahrenheit to Celsius using the formula: (F - 32) * 5/9
celsius = (fahrenheit - 32) * 5.0 / 9.0;
// Display the converted temperature in Celsius
printf("The temperature in Celsius is: %.2lf degrees Celsius\n", celsius);
return 0;
}
Here’s a breakdown of the program:
- We include the
stdio.h
header for input and output functions. - We declare two variables:
fahrenheit
(to store the temperature in Fahrenheit) andcelsius
(to store the converted temperature in Celsius). - We use
printf
to ask the user to enter the temperature in Fahrenheit andscanf
to read the input and store it in thefahrenheit
variable. - We convert the temperature from Fahrenheit to Celsius using the formula:
(F - 32) * 5/9
, whereF
is the temperature in Fahrenheit. - Finally, we use
printf
to display the converted temperature in Celsius with two decimal places.
To run this program, follow these steps:
- Open a C compiler (like GCC) on your computer.
- Copy and paste the program into a new C file (e.g.,
temp_conversion.c
). - Compile the program by running
gcc temp_conversion.c -o temp_conversion
in the command prompt or terminal. - Run the program by typing
./temp_conversion
and providing the temperature in Fahrenheit when prompted.
The program will then calculate and display the temperature in Celsius based on the Fahrenheit input you provide.