Write a program in C++ and python to convert temperature from Fahrenheit to Celsius and vice-versa

By | October 4, 2021
Write a program in C++ and python to convert temperature from Fahrenheit to Celsius and vice-versa

In this program first, we will ask the user whether he wants to change the temperature from Fahrenheit to Celsius or vice versa and then accept a temperature and convert it.

Conversion formula

Celsius to Fahrenheit:   (°C × 9/5) + 32 = °F

Fahrenheit to Celsius:   (°F − 32) × 5/9 = °C

 

Vamware

C:

#include<stdio.h> 

int main() 
{
   float f, c;
   int option;
   printf("Enter  1 to change temperature from Fahrenheit to Celsius\n");
   printf("Enter 2 to change temperature from Celsius to Fahrenheit\n");
   scanf("%d", &option);
   
   if(option ==1)
   {
   	printf("Enter Temperature in Fahrenheit: ");
   	scanf("%f", &f);
   	c= (f-32)/1.8;
   	printf("%.2f C",c);
   }
   if(option==2)
   {
   	printf("Enter Temperature in Celsius: ");
   	scanf("%f", &c);
   	f=(1.8*c)+32;
   	printf("%.2f F",f);
   }

    return 0;
}

Output

Vamware
Enter 1 to change temperature from Fahrenheit to Celsius
Enter 2 to change temperature from Celsius to Fahrenheit
1
Enter Temperature in Fahrenheit: 34
1.11 C

C++:

#include<iostream.h>
#include< conio.h>
#include<stdio.h>
#include<math.h>

void main()
{
clrscr();
float ut,ct;
int ch;
cout<<"Enter 1 to change temperature from Fahrenheit to Celsius\n";
cout<<"Enter 2 to change temperature from Celsius to Fahrenheit\n";
cin>>ch;
if (ch==1)
{cout<<"Enter Temperature in Fahrenheit: ";
cin>>ut;
ct= (ut-32)/1.8;
cout<<ct<<" C";
}
if (ch==2)
{
cout<<"Enter Temperature in Celsius: ";
cin>>ut;
ct=(1.8*ut)+32;
cout<<ct<<" F";
}
getch();
}

Output:

Enter 1 to change temperature from Fahrenheit to Celsius
Enter 2 to change temperature from Celsius to Fahrenheit
2
Enter Temperature in Celsius: 12
53.6 F

 

Python:

print("Enter 1 to change temperature from Fahrenheit to Celsius")
print("Enter 2 to change temperature from Celsius to Fahrenheit")
ch = int(input(""))
if ch==1:
    ut= float(input("Enter Temperature in Fahrenheit: " ))
    ct=(ut-32)/1.8
    print(ct,"C")
if ch==2:
    ut= float(input("Enter Temperature in Celsius: " ))
    ct=(1.8*ut)+32
    print(ct,"F")

Output:

Enter 1 to change temperature from Fahrenheit to Celsius
Enter 2 to change temperature from Celsius to Fahrenheit
1
Enter Temperature in Fahrenheit: 23
-5.0 C

People are also reading:

Author: Vinay

I am a Full Stack Developer with a Bachelor's Degree in Computer Science, who also loves to write technical articles that can help fellow developers.

Leave a Reply

Your email address will not be published.