9.14

发布时间 2023-09-14 21:19:33作者: 徐星凯

消除double类型计算出现精度损失的方法

package BigDecimalTest;
import java.math.BigDecimal;

public class TestBigDecimal
{
    public static void main(String[] args) 
    {
        BigDecimal f1 = new BigDecimal("0.05");
        BigDecimal f2 = BigDecimal.valueOf(0.01);
        BigDecimal f3 = new BigDecimal(0.05);
        System.out.println("下面使用String作为BigDecimal构造器参数的计算结果:");
        System.out.println("0.05 + 0.01 = " + f1.add(f2));
        System.out.println("0.05 - 0.01 = " + f1.subtract(f2));
        System.out.println("0.05 * 0.01 = " + f1.multiply(f2));
        System.out.println("0.05 / 0.01 = " + f1.divide(f2));
        System.out.println("下面使用double作为BigDecimal构造器参数的计算结果:");
        System.out.println("0.05 + 0.01 = " + f3.add(f2));
        System.out.println("0.05 - 0.01 = " + f3.subtract(f2));
        System.out.println("0.05 * 0.01 = " + f3.multiply(f2));
        System.out.println("0.05 / 0.01 = " + f3.divide(f2));
    }
}

 value()可以将小括号内的内容转为字符串类型

package Doubletest;
public class TestDouble {

    public static void main(String args[]) {
        System.out.println("0.05 + 0.01 = " + (0.05 + 0.01));
        System.out.println("1.0 - 0.42 = " + (1.0 - 0.42));
        System.out.println("4.015 * 100 = " + (4.015 * 100));
        System.out.println("123.3 / 100 = " + (123.3 / 100));
    }
}

 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

生成界面实现两数相加输出

package AdditionTest;
// An addition program 

import javax.swing.JOptionPane;  // import class JOptionPane

public class Addition {
   public static void main( String args[] )
   {
      String firstNumber,   // first string entered by user
             secondNumber;  // second string entered by user
      int number1,          // first number to add
          number2,          // second number to add
          sum;              // sum of number1 and number2

      // read in first number from user as a string
      firstNumber =
         JOptionPane.showInputDialog( "Enter first integer" );

      // read in second number from user as a string
      secondNumber =
         JOptionPane.showInputDialog( "Enter second integer" );

      // convert numbers from type String to type int
      number1 = Integer.parseInt( firstNumber ); 
      number2 = Integer.parseInt( secondNumber );

      // add the numbers
      sum = number1 + number2;

      // display the results
      JOptionPane.showMessageDialog(
         null, "The sum is " + sum, "Results",
         JOptionPane.PLAIN_MESSAGE );

      System.exit( 0 );   // terminate the program
   }
}