Fahrenheit to Celsius conversion yields only 0.0 and -0.0

笑着哭i 提交于 2019-11-27 09:33:48

In integer math (5 / 9) = 0.

and (degrees - 32) * (5 / 9); will always be 0 you need to use doubles or something.

The problem seems to be 5/9. They are seen as an integer, and 5/9 is 0.something which is 0 as an integer. So whatever * 0 = +-0 :)

Place a "d" after the numbers, (5d/9d) forcing the compiler to consider them doubles.

change (5 / 9) to (5.0 / 9.0) to let java know, that you want real numbers division.

If you don't return anything set the return type to void. If you like to return doubles, you have to use doubles in calculations. 5/9 is always zero because 5 and 9 are integers. 5.0/9.0 is a different calculation on doubles.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.DecimalFormat;

public class FCConverter
{
  private double Celsius;
  private double Fahrenheit;
  public void setFahrenheit (double degrees)
  {
     Celsius = (degrees - 32.0) * (5.0 / 9.0);
  }
  public double getCelsius ()
  {
      return Celsius;
  }
  public void setCelsius (double degrees)
  {
      Fahrenheit = (degrees * 9.0 / 5.0 + 32.0);
  }
  public double getFahrenheit ()
  {
      return Fahrenheit;
  }
}
Alessio
import java.util.Scanner;
public class HelloWorld {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);  // Reading from System.in

        System.out.println("Enter  the number of Fahrenheit temperatures to convert to Kelvins");
// opts for the user to enter a number 

        int F = reader.nextInt() ; // Scans the next token of the input
        double f = 5/9d;
        System.out.println(f);
        double x = F -32;
        System.out.println(x);
        double K = (f*x)+ 273.0; // the formulae to calculate temperature  in Kelvin
        System.out.println( +F + " Fahrenheit is equal " +K + " Kelvins" ) ;
        reader.close();




    }       

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!