在開發應用程序時,我發現了一個嚴重的錯誤。但首先是一些細節:我想在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);
}
}
問候和感謝提前,
朱利安