Yêu cầu
– Nhập vào mảng 1 chiều số thực
– Tìm vị trí trong mảng 1 chiều các số thực mà giá trị tại đó gần x nhất
Ví dụ:
Cho mảng số thực 2.3 -4.5 6.5 -9.6 4.2
Số thực x = -4.5
Khoảng cách giữa x và các giá trị trong mảng: 6.8 0 11 5.1 8.7
Giá trị gần x nhất là -4.5, vị trí là 2
Giải thuật
– Dùng vòng lặp for() và câu lệnh if() để kiểm tra.
Code
package net.vncoding; import java.util.Scanner; import java.lang.Math; public class JavaCore { static float arr[] = {1, -3.0f, -9.6f, 7, 8.9f, -12.3f, -23, 2, 20}; public static void main(String[] args) { float x; System.out.print("Input x = "); Scanner sc = new Scanner(System.in); x = sc.nextFloat(); int pos = find_pos_nearest_x(arr, x); System.out.println("Position of element is nearest " + x + " is " + (pos+1)); sc.close(); } public static int find_pos_nearest_x(float arr[], float x) { float sub = Math.abs(arr[0] - x); int i, pos = 0; for(i = 1; i < arr.length; i++) { if(sub > Math.abs(arr[i] - x)) { sub = Math.abs(arr[i] - x); pos = i; } } return pos; } }
Kết quả
Leave a Reply
You must be logged in to post a comment.