2015-07-10 54 views
1

在开发应用程序时,我发现了一个严重的错误。但首先是一些细节:我想在GUI上显示温度。温度是双倍值。用户应该能够增加/降低温度。目标是模拟加热单元的加热/温度阀门。除了具有随机值之外,用户应该能够通过使用GUI来增加/减少该值。基本上这个值在启动时初始化为20.1(只是我在开始设置的一个随机值)。降低双倍值的奇怪错误

我注意到一个奇怪的行为,当我试图降低温度。一切工作都会在增加时发挥作用。但降低温度(按步骤1)会导致以下情况:20.1,19.1,18.1,17.1,16.1,然后是15.100000000000001,14.100000000000001等。

是什么原因? 使用以.1结尾的值时,错误会发生。因此,使用22.1或31.1的基础值进行尝试时没有任何区别。

错误总是从16.1至15的变化时...

它可再现每次。我已经写了一个测试程序,随意尝试:

package devices; 

import java.awt.EventQueue; 
import java.awt.Font; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 

public class Test extends JFrame { 

/** 
* the temperature 
*/ 
private Double temp = 20.1; 
private JPanel contentPane; 

/** 
* Launch the application. 
*/ 
public static void main(String[] args) { 
    EventQueue.invokeLater(new Runnable() { 
     @Override 
     public void run() { 
      try { 
       Test frame = new Test(); 
       frame.setVisible(true); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

/** 
* Create the frame. 
*/ 
public Test() { 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setBounds(100, 100, 271, 152); 
    contentPane = new JPanel(); 
    setContentPane(contentPane); 
    contentPane.setLayout(null); 

    final JLabel lblNewLabel = new JLabel(""); 
    lblNewLabel.setBounds(10, 11, 235, 56); 
    lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 19)); 
    lblNewLabel.setText(String.valueOf(temp)); 
    contentPane.add(lblNewLabel); 

    JButton btnNewButton_1 = new JButton("Increase"); 
    btnNewButton_1.addActionListener(new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent e) { 
      temp = temp + 1; 
      lblNewLabel.setText(String.valueOf(temp)); 
     } 
    }); 
    btnNewButton_1.setBounds(10, 78, 101, 23); 
    contentPane.add(btnNewButton_1); 

    JButton btnNewButton = new JButton("Decrease"); 
    btnNewButton.setBounds(137, 78, 108, 23); 
    btnNewButton.addActionListener(new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent e) { 
      temp = temp - 1; 
      lblNewLabel.setText(String.valueOf(temp)); 
     } 
    }); 
    contentPane.add(btnNewButton); 
} 

} 

问候和感谢提前,

朱利安

回答

1

0.1是不是二进制一个整数,这样你就可以” t总是以十分之一秒为单位。示例here。如果十分之一是你所需要的精细分辨率,将它们存储为int和手动显示它们:

(temp/10).toString() +"."+(temp℅10).toString() 

这是什么的Turbo Pascal没有为金钱数额,例如。

0

Double和其他默认浮点表示是无限范围os值(两个整数之间有无限值:1,1.1,1.11,1.11,... 2)的离散表示。

因此,很多值没有完全表示。

您应该将您的号码四舍五入到所需的精度。