C Program to convert temp from Fahrenheit to Celsius
Objective
Write a C program to convert temperature from Fahrenheit to Celsius.
Algorithm / Approach
- Declare float variables
fandc. - Read the temperature in Fahrenheit from the user.
- Apply the conversion formula:
c = (5.0 / 9.0) * (f - 32). - Print the Celsius result.
main.c
#include<stdio.h>
int main( ) {
float c,f;
printf("Enter Temp in (F) : ");
scanf("%f",&f);
c = (5.0/9.0)*(f-32);
printf("Temp in Celsius : %f\n",c);
return 0;
}
Expected Output
Enter Temp in (F): 42 Temp in Celsius: 5.55556
Explanation of the Program
- The formula to convert Fahrenheit to Celsius is: C = (5/9) * (F - 32).
- However, notice that we wrote
5.0/9.0instead of5/9. This is extremely important in C! If you write5/9, C performs Integer Division, which truncates the decimal part and results in exactly 0. Your entire calculation would become 0 * (f - 32) = 0. - By adding the
.0, we force the compiler to perform Floating-Point Division, which correctly yields 0.5555...
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Using
5/9instead of5.0/9.0, which causes the entire formula to always evaluate to 0 due to integer division truncation.