0

我必须将摄氏温度转换为华氏温度。但是,当我以摄氏度打印温度时,我得到了错误的答案!请帮忙 !(公式是 c = (5/9) * (f -32)。当我输入 1 代表华氏度时,我得到 c = -0.0。我不知道出了什么问题:s

这是代码

import java.io.*; // import/output class
public class FtoC { // Calculates the temperature in Celcius
    public static void main (String[]args) //The main class
    {
    InputStreamReader isr = new InputStreamReader(System.in); // Gets user input
    BufferedReader br = new BufferedReader(isr); // manipulates user input
    String input = ""; // Holds the user input
    double f = 0; // Holds the degrees in Fahrenheit
    double c = 0; // Holds the degrees in Celcius
    System.out.println("This program will convert the temperature from degrees Celcius to Fahrenheit.");
    System.out.println("Please enter the temperature in Fahrenheit: ");
    try {
        input = br.readLine(); // Gets the users input
        f = Double.parseDouble(input); // Converts input to a number
    }
    catch (IOException ex)
    {
        ex.printStackTrace();
    }
    c = ((f-32) * (5/9));// Calculates the degrees in Celcius
    System.out.println(c);
    }
}
4

5 回答 5

4

You are doing integer division, and hence 5 / 9 will give your 0.

Change it to floating point division: -

c = ((f-32) * (5.0/9));

or, do the multiplication first (Remove the brackets from division): -

c = (f-32) * 5 / 9;

Since, f is double. Numerator will be double only. I think this way is better.

于 2012-12-19T06:32:53.457 回答
0

You should try using double instead of int as this would lead to loss of precision. Instead of using the whole formula, use one calculation at one time

Example: Use appropriate casting Double this = 5/9

F - Double 32

于 2012-12-19T06:34:24.330 回答
0

use this rather:

c = (int) ((f-32) * (5.0/9));// Calculates the degrees in Celcius 

as it involves division and you should not use only ints to get proper division

于 2012-12-19T06:35:31.413 回答
0

用这个

System.out.println((5F / 9F) * (f - 32F));
于 2012-12-19T06:39:17.490 回答
0

除非另有明确规定,Java 将所有数字视为整数。由于整数不能存储数字的小数部分,因此在执行整数除法时,余数被丢弃。所以:5/9 == 0

Rohit 的解决方案c = (f-32) * 5 / 9;可能是最简洁的(尽管缺少显式类型可能会导致一些混乱)。

于 2012-12-19T07:36:58.147 回答