Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to convert temp from Fahrenheit to Celsius.

Java Code Example — Basic Programs

ADVERTISEMENT

Java Program to convert temp from Fahrenheit to Celsius.

Objective

Write a Java program to convert temperature from Fahrenheit to Celsius.

Algorithm / Approach

  1. Prompt the user to enter a temperature in Fahrenheit.
  2. Apply the conversion formula: C = (5.0 / 9.0) * (F - 32).
  3. Store the result in a double variable 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.0 to perform floating-point division instead of integer division.

Complexity

Time Complexity O(1)
Space Complexity O(1)

Common Mistakes

  • Using 5/9 instead of 5.0/9.0, which results in 0 due to integer division.
ADVERTISEMENT