Tuesday 7 July 2020

Python code to convert Fahrenheit into celsius


Fahrenheit to Celsius Function

Problem Description: You are given with three values - Start Fahrenheit Value (S), End
Fahrenheit value (E) and Step Size (W), you need to convert all Fahrenheit values from Start to
End at the gap of W, into their corresponding Celsius values and print the table.
How to approach?
1. Initialize a variable currentvalue with start.
2. Run a while loop till currentvalue is less than equal to the end.
3. Calculate the fahrenheit value for each currentvalue by using the conversion formula
fahrenheitValue = (5.0/ 9) * (currentvalue - 32).
4. Print currentvalue and its corresponding fahrenheit value.
5. Increment currentvalue by step W.
Pseudo Code for this problem:
currentvalue=start
While currentvalue less than or equal to end:
 fahrenheitValue = (5.0/ 9) * (currentvalue - 32)
 Print(currentvalue fahrenheitValue)
 Increment currentvalue by W.
❏ Let us dry run the code for
Start = 0
End = 100
Step = 20
➔ Currentvalue= 0
 fahrenheitValue=-17
 print : 0 -17
➔ Currentvalue= 20
 fahrenheitValue= -6
 print : 20 -6
➔ Currentvalue= 40
 fahrenheitValue=4
 print : 40 4
➔ Currentvalue= 60
 fahrenheitValue=15
 print : 60 15
➔ Currentvalue= 80
 fahrenheitValue=26
 print : 80 26
➔ Currentvalue= 100
 fahrenheitValue=37
 print :100 37

Final Output:
 0 -17
 20 -6
 40 4
 60 15
 80 26
 100 37

Given three values - Start Fahrenheit Value (S), End Fahrenheit value (E) and Step Size (W), you need to convert all Fahrenheit values from Start to End at the gap of W, into their corresponding Celsius values and print the table.

Input Format :
3 integers - S, E and W respectively

Output Format :
Fahrenheit to Celsius conversion table. One line for every Fahrenheit and Celsius Fahrenheit value. Fahrenheit value and its corresponding Celsius value should be separate by tab ("\t")

Constraints :
0 <= S <= 1000
0 <= E <= 1000
0 <= W <= 1000

CODE:

def printTable(start,end,step):
    while(start <= end):
        C = (start - 32) * (5/9)
        print(start,"\t",int( C))
        start = start + step
        pass 
    
    
s = int(input())
e = int(input())
step = int(input())
printTable(s,e,step)


Sample Input 1:

100 
20

Sample Output 1:
0 -17
20 -6
40 4
60 15
80 26
100 37

Sample Input 2:
120 
200 
40

Sample Output 2:
120 48
160 71
200 93

Explanation for Sample Output 2 :
Start value is 120, end value is 200 and step size is 40. Therefore, the values we need to convert are 120, 120 + 40 = 160, and 160 + 40 = 200. 
The formula for converting Fahrenheit to Celsius is:
Celsius Value = (5/9)*(Fahrenheit Value - 32)  
Plugging 120 into the formula, the celsius value will be (5 / 9)*(120 - 32) => (5 / 9) * 88 => (5 * 88) / 9 => 440 / 9 => 48.88
But we'll only print 48 because we are only interested in the integral part of the value.


No comments:

Post a Comment