Read a temperature with decimals and convert it, keeping the arithmetic in doubles.
What to build
A temperature converter from Celsius to Fahrenheit and kelvin.
Requirements
- Read a temperature in Celsius (it may have decimals).
- Print
C C = F F = K Kwith each value to one decimal place, for example25.0 C = 77.0 F = 298.2 K.
Input
One number.
Output
One line.
Constraints
-273.15 ≤ C ≤ 10000.
Example
Input:
25
Output:
25.0 C = 77.0 F = 298.2 K
Why it works
Reading a double and multiplying by 9 before dividing by 5 keeps the fraction, which int arithmetic would lose.
Examples
Example 1 · Input
25
Expected output
25.0 C = 77.0 F = 298.2 K
Example 2 · Input
-40
Expected output
-40.0 C = -40.0 F = 233.1 K
Hints
Hint 1
Read a double with nextDouble(); F = C × 9 / 5 + 32 and K = C + 273.15.
Hint 2
Use printf with %.1f for one decimal.
Solution
Show one correct solution (try it yourself first)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double c = in.nextDouble();
double f = c * 9 / 5 + 32;
double k = c + 273.15;
System.out.printf("%.1f C = %.1f F = %.1f K%n", c, f, k);
}
}