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
doubleto keep the decimals. - Write
9.0 / 5, not9 / 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 / 5is a decimal division (1.8). With9 / 5the answer would be1.printfwith%.1fprints 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. |