Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java คูณเลขทศนิยม (Floating-Point Numbers)

ในบทความนี้ เราจะเรียนรู้วิธีคูณเลขทศนิยม (Floating-Point Numbers) ในภาษา Java

ข้อมูลเกี่ยวกับ float

  • float: 32-bit IEEE 754 single-precision, ค่าเริ่มต้น 0.0f
  • double: 64-bit double-precision, ค่าเริ่มต้น 0.0d (แม่นยำกว่า)
  • ไม่ควรใช้ float/double สำหรับเงิน/การเงิน (ใช้ BigDecimal แทน)

ตัวอย่างการทำงาน

อินพุต:

Value_1: 12.4f
Value_2: 15.7f

เอาต์พุต:

Result: 194.68

อัลกอริทึม

  1. เริ่มต้นโปรแกรม
  2. ประกาศตัวแปร float 3 ตัว: input_1, input_2, product
  3. รับค่าจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
  4. คูณด้วยตัวดำเนินการ *
  5. แสดงผลลัพธ์
  6. จบโปรแกรม

ตัวอย่างที่ 1: รับค่าจากผู้ใช้

import java.util.Scanner;

public class MultiplyFloatValues {
    public static void main(String[] args) {
        float input_1, input_2, my_prod;

        Scanner my_scan = new Scanner(System.in);
        System.out.println("A reader object has been defined");
        System.out.println("Enter the first floating point number: ");
        input_1 = my_scan.nextFloat();
        System.out.println("Enter the second floating point number: ");
        input_2 = my_scan.nextFloat();

        my_prod = input_1 * input_2;
        System.out.println("\nThe product of the two values is: " + my_prod);
    }
}

ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า

public class MultiplyFloatValues {
    public static void main(String[] args) {
        float value_1 = 12.4f, value_2 = 15.7f, my_prod;

        System.out.printf("The two numbers are %.2f and %.2f ", value_1, value_2);
        my_prod = value_1 * value_2;
        System.out.println("\nThe product of the two values are: " + my_prod);
    }
}

ข้อควรระวังเรื่องความแม่นยำ

float f = 0.1f + 0.2f; // 0.300000012 (ไม่แม่นยำ)
double d = 0.1 + 0.2;  // 0.30000000000000004 (ไม่แม่นยำ)

// สำหรับการเงิน ใช้ BigDecimal
BigDecimal bd1 = new BigDecimal("0.1");
BigDecimal bd2 = new BigDecimal("0.2");
BigDecimal sum = bd1.add(bd2); // 0.3 แม่นยำ