Java Program to convert temp from Fahrenheit to Celsius.
Objective
Write a Java program to convert temperature from Fahrenheit to Celsius.
Algorithm / Approach
- Prompt the user to enter a temperature in Fahrenheit.
- Apply the conversion formula:
C = (5.0 / 9.0) * (F - 32). - Store the result in a
doublevariable and print it.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter temp in (F): ");
int f = s.nextInt();
double c = (5.0/9.0)*(f-32);
System.out.print("Temp in (C) = "+c);
}
}
Expected Output
Enter temp in (F): 41 Temp in (C) = 5.0
Explanation of the Program
- The user inputs the temperature in Fahrenheit into the variable
f. - The formula
(5.0/9.0) * (f - 32)converts the temperature to Celsius. - It uses
5.0 / 9.0to perform floating-point division instead of integer division.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Using
5/9instead of5.0/9.0, which results in 0 due to integer division.