Are you looking for a C program that can perform temperature conversion such as Celsius to Fahrenheit and Fahrenheit to Celsius? then you are at the right place. Here you can actually get the choice from the user and perform the Temperature Conversion and print the result according to the user input.
Here is the Complete C program to “Convert Fahrenheit to Celsius & Celsius to Fahrenheit”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
#include <stdio.h> int main() { // declare the variables double tmp, result; char *choice_text; // get the choice from the user int choice; printf("Select your choice: \n"); printf("1. Celsius to Fahrenheit \n2. Fahrenheit to Celsius\n"); printf("Enter your choice: "); scanf("%d", &choice); // let's use switch case to find the temperature switch(choice) { case 1: printf("Enter the temperature in Celsius: "); scanf("%lf", &tmp); choice_text = "Fahrenheit"; //formula to convert F to C result = (tmp * 9 / 5) + 32; break; case 2: printf("Enter the temperature in Fahrenheit: "); scanf("%lf", &tmp); choice_text = "Celsius"; //formula to convert C to F result = (tmp - 32) * 5 / 9; break; // print default incase if the user does not select 1 or 2 default: printf("Sorry Invalid choice, you can either select 1 or 2! \n"); return 0; } // Printing out the result according to the computation printf("Temperature in %s is: %.1f", choice_text, result); return 0; } |
Please go through the inline comments to understand how the program works.
These are the sample output of the above C program:
1 2 3 4 5 6 7 8 9 |
Select your choice: 1. Celcius to Fahrenheit 2. Fahrenheit to Celcius Enter your choice: 1 Enter the temperature in Celcius: 37 Temperature in Fahrenheit is: 98.6 -------------------------------- Process exited after 2.554 seconds with return value 0 Press any key to continue . . . |
1 2 3 4 5 6 7 8 9 |
Select your choice: 1. Celsius to Fahrenheit 2. Fahrenheit to Celsius Enter your choice: 2 Enter the temperature in Fahrenheit: 100 Temperature in Celsius is: 37.8 -------------------------------- Process exited after 2.059 seconds with return value 0 Press any key to continue . . . |
I hope this program is helpful for beginners C programming language learners and school/college students.