Convert Celsius to Fahrenheit

Description: Write a method toFahrenheit(double celsius) using F = C x 9 / 5 + 32. Print the result for 0, 37 and 100 degrees.

Hint:

  • Use double to keep the decimals.
  • Write 9.0 / 5, not 9 / 5 (that is integer division).

Solution

public class Main {
    static double toFahrenheit(double celsius) {
        return celsius * 9.0 / 5 + 32;
    }

    public static void main(String[] args) {
        for (double c : new double[]{0, 37, 100}) {
            System.out.printf("%.1f C = %.1f F%n", c, toFahrenheit(c));
        }
    }
}
Output

0.0 C = 32.0 F
37.0 C = 98.6 F
100.0 C = 212.0 F

How it works

  • 9.0 / 5 is a decimal division (1.8). With 9 / 5 the answer would be 1.
  • printf with %.1f prints one digit after the decimal point.

Read Java Methods.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.