문제

I'm writing a program that does many things, but one of them is converting Celcius to Fahrenheit. After I did this, I decided to allow the reverse, so that's what I've done. I get correct answers when I convert Celcius to Fahrenheit, but for some reason I'm getting slightly off answers when converting Fahrenheit to Celcius. Here's my code:

String celcius = jTextArea3.getText();
String fahren = jTextArea7.getText();
if (fahren.equals("")) {
    double tempFahr;
    double Input = Double.parseDouble(jTextArea3.getText());

     tempFahr = Input * 9 / 5 + 32;
        jTextArea7.setText(tempFahr + "");
}
else
{
    double tempCelc;
    double Input = Double.parseDouble(jTextArea7.getText());

     tempCelc = (Input -32) * 5 / 9;
        jTextArea3.setText(tempCelc + "");
}

It's simple code, but I'm wondering if it could be something very small that I'm not seeing. It could be my formula I suppose, but I'm pretty sure it's not, I've looked into it. Can anyone help?

An example of the off answers I get is: 1 Celcius = 33.8 Fahrenheit 33.8 Fahrenheit = 0.9999999999999984 Celcius

도움이 되었습니까?

해결책

@Greg is right

You just need to do some rounding:

final int precision = 6 // try some different values here, from 2 to... 8?

jTextArea3.setText(String.format("%." + precision + "f", tempCelc));

Anyway - don't worry your values are just fine, but to compare (or print, which is current use case) them you need some epsilon/precision, because - again: floating point calculations are almost never "exact".

다른 팁

Because Java uses IEEE binary representations of floating point numbers, floating point calculations are almost never "exact". The problem is that 33.8 cannot be represented exactly, it's internally 33.799999999999996 or something. When you convert that back to Celsius, you get a number ever so slightly less than 1.

As always, the relevant reference for this is What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Floating-point inaccuracies will be very obvious when using Double.toString() (or its implicit equivalent). Instead prefer String.format("%.3f", value) or your choice of precision.

Side note: In Java, regardless of the data type you're assigning to, dividing an integer by an integer yields an integer. Be careful when refactoring your code, as something that looks similar may unintentionally round a factor in your result. (Read the second paragraph of this section of the Java Language Specification for details.)

double test = 3 / 2;   // yields 2
double test = 3 / 2.0; // yields 1.5

The slight difference in the values is simply the result of floating-point inaccuracies. Decimal values cannot be represented to exact values in binary (what computers use internally), resulting in extremely small differences at the level of 10^-16 or so. This topic is covered quite nicely (although with Python) in this article.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top