Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chương trình Java nhân hai số thực (floating-point)


Trong bài viết này, chúng ta sẽ tìm hiểu cách nhân hai số thực (floating-point) trong Java. Số thực là số có phần thập phân. Kiểu float là đơn độ chính xác 32-bit IEEE 754. Dùng để tiết kiệm bộ nhớ cho mảng lớn số thực. Giá trị mặc định 0.0f. Không dùng cho giá trị chính xác như tiền tệ.

Dưới đây là minh họa:

Đầu vào

Giả sử đầu vào:

Giá trị 1: 12.4f, Giá trị 2: 15.7f

Đầu ra

Kết quả mong đợi:

Kết quả: 194.68f

Thuật toán

Bước 1 - BẮT ĐẦU
Bước 2 - Khai báo 3 số thực: input_1, input_2, product
Bước 3 - Nhập hai số thực từ người dùng hoặc định nghĩa trước
Bước 4 - Đọc giá trị
Bước 5 - Nhân hai giá trị dùng toán tử *
Bước 6 - Hiển thị kết quả
Bước 7 - DỪNG

Ví dụ 1: Nhập từ bàn phím

Người dùng nhập dựa trên lời nhắc. Thử trực tiếp trong coding ground.

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);
    }
}

Đầu ra

A reader object has been defined
Enter the first floating point number: 12.4
Enter the second floating point number: 15.7
The product of the two values is: 194.68

Ví dụ 2: Giá trị định nghĩa trước

Hai số đã được định nghĩa trước.

public class MultiplyFloatValues {
    public static void main(String[] args) {
        float value_1, value_2, my_prod;
        value_1 = 12.4f;
        value_2 = 15.7f;
        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);
    }
}

Đầu ra

The two numbers are 12.40 and 15.70
The product of the two values are: 194.68