0

I'm trying to write a program that converts temperatures expressed in degree Fahrenheit to degree Celsius. The user enters a Fahrenheit value and the program prints out the Celsius value. The user is supposed to enter 212 as the Fahrenheit value the program is supposed to calculate 100.0 as the Celsius value but instead I'm getting 0.0 as the Celsius value when I want to get 100.0

I'm not sure where the problem might be. Is it possibility the order of operations?

The formula for converting Celsius to Fahrenheit is : C = 5 / 9 (F - 32)

import acm.program.*; 

public class FahrenheitToCelsius extends ConsoleProgram {

    public void run() {
        println("This program converts Fahrenheit to Celsius");
        int fah = readInt("Enter Fahrenheit temperature: ");
        double ft = 5 / 9;
        double cel = ft * (fah - 32);
        println("Celsius equivalent = " + cel);
    }
}
Old Pro
  • 24,624
  • 7
  • 58
  • 106
Jessica M.
  • 1,451
  • 12
  • 39
  • 54

3 Answers3

4

5 / 9 is an integer division, so it'll return a 0 even though you're assigning it to a double.
Try 5.0 / 9.

tzaman
  • 46,925
  • 11
  • 90
  • 115
2
double ft = 5 / 9 ;

The line above doesn't do what you think it does.
Because 5 and 9 are both integers, it does integer division. The fact that you're assigning the result to a double doesn't matter, if both operands are integers, you will get integer math.

So ft is always 0, so cel is always 0

Try

double ft = 5.0/9.0;
Tim
  • 6,406
  • 22
  • 34
0

When you operate on two integers, results is not converted to double. It remains as int only. To get the result into double, at least one of the numbers should be double. e.g.

       double ft = 5.0/9; //double
       double ft = 5/9.0;//double
       double ft = 5.0/9.0;//double

While

        double ft = 5/9; //int 0

Please refer the Floating Point Operations Specification for details.

Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73