2015-07-10 88 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)的離散表示。

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

您應該將您的號碼四捨五入到所需的精度。