Java华氏转摄氏循环程序问题:如何输出带小数的摄氏温度?
Hey there! Let's figure out why your Celsius temperature outputs aren't showing decimal places and fix it up quickly.
The Root Cause
The most common reason this happens is integer division in Java. If you're using int (integer) variables for your calculations, Java will automatically discard any fractional part of the result. For example, if you have code like this:
int fahrenheit = 77; int celsius = (fahrenheit - 32) * 5 / 9; // Result is 25 instead of 25.0
The integer operation strips away all decimal values, leaving you with whole numbers only.
Solutions to Show Decimal Places
Here are three straightforward ways to fix this:
Use Floating-Point Variables for Calculations
Switch your Celsius variable to adouble(orfloat) and use floating-point literals (like5.0instead of5) in your formula to trigger floating-point division:double celsius = (fahrenheit - 32) * 5.0 / 9.0;This ensures the calculation keeps fractional values instead of truncating them.
Add Explicit Type Casting
If you need to keep some variables as integers, cast one part of the calculation to adoubleto force floating-point math:int fahrenheit = 77; double celsius = (double)(fahrenheit - 32) * 5 / 9; // Casts the difference to double firstThe cast converts the integer result of
fahrenheit - 32to a double, so the rest of the division will preserve decimals.Format Output to Specify Decimal Places
Even if you have a floating-point result, Java might not always show trailing decimals by default. UseSystem.out.printf()(orString.format()) to define exactly how many decimal places to display:// Example: Show 2 decimal places System.out.printf("Fahrenheit: %d → Celsius: %.2f%n", fahrenheit, celsius);The
%.2fformat specifier tells Java to format the floating-point number with 2 decimal places. You can change2to any number (like%.1ffor one decimal,%.3ffor three) based on your needs.
Full Example Code
Here's a complete working version that combines these fixes:
public class TemperatureConverter { public static void main(String[] args) { // Loop through a range of Fahrenheit temperatures for (int fahrenheit = 0; fahrenheit <= 100; fahrenheit += 10) { // Calculate Celsius with floating-point math double celsius = (fahrenheit - 32) * 5.0 / 9.0; // Format output to show 2 decimal places System.out.printf("Fahrenheit: %3d → Celsius: %.2f%n", fahrenheit, celsius); } } }
Expected Output
Running this code will give you output like:
Fahrenheit: 0 → Celsius: -17.78
Fahrenheit: 10 → Celsius: -12.22
Fahrenheit: 20 → Celsius: -6.67
Fahrenheit: 30 → Celsius: -1.11
Fahrenheit: 40 → Celsius: 4.44
Fahrenheit: 50 → Celsius: 10.00
Fahrenheit: 60 → Celsius: 15.56
Fahrenheit: 70 → Celsius: 21.11
Fahrenheit: 80 → Celsius: 26.67
Fahrenheit: 90 → Celsius: 32.22
Fahrenheit: 100 → Celsius: 37.78
内容的提问来源于stack exchange,提问作者Marc

