Program 4.6: Using Parentheses to change the order of evaluation

Sometimes the default order of evaluation isn't what you want. For instance the formula to change a Fahrenheit temperature to a Celsius temperature is C=(5/9)(F - 32).You must subtract 32 from the Fahrenheit temperature before you multiply by 5/9, not after. You can use parentheses to adjust the order much as they are used in the above formula. Program 4.6 prints a table showing the conversions from Fahrenheit and Celsius between zero and two hundred degrees Fahrenheit every ten degrees.2

// Print a Fahrenheit to Celsius table

class FahrToCelsius  {

  public static void main (String args[]) {
  
    double fahr, celsius;
    double lower, upper, step;

    // lower limit of temperature table
    lower = 0.0;  

    // upper limit of temperature table
    upper = 300.0;

    // step size
    step  = 20.0; 
 
    fahr = lower;
    while (fahr <= upper) { 
      celsius = (5.0 / 9.0) * (fahr-32.0);
      System.out.println(fahr + " " + celsius);
      fahr = fahr + step;
    } 

  } 

} 
As usual here's the output:

% javac FahrToCelsius.java
% java FahrToCelsius
0 -17.7778
20 -6.66667
40 4.44444
60 15.5556
80 26.6667
100 37.7778
120 48.8889
140 60
160 71.1111
180 82.2222
200 93.3333
220 104.444
240 115.556
260 126.667
280 137.778
300 148.889
%

Copyright 1996 Elliotte Rusty Harold
elharo@sunsite.unc.edu
This Chapter
Examples
Home