Yêu cầu
– Nhập vào mảng 1 chiều số thực
– Viết hàm tìm giá trị dương đầu tiên trong mảng 1 chiều số thực. Nếu mảng không có số dương, trả về -1.
Giải thuật
– Dùng vòng lặp for() và câu lệnh if() để tìm số dương.
Code
package net.vncoding; public class JavaCore { static float arr[] = {-1.3f, -3.3f, -9, 0, 8, 16, 23}; public static void main(String[] args) { float num = find_positive_element(arr); if(num == -1) System.out.println("All elements of array is negative"); else System.out.println("The first positive element of arry is " + num); } public static float find_positive_element(float arr[]) { float num = -1; int i; for(i = 0; i < arr.length; i++) { if(arr[i] > 0) { num = arr[i]; break; } } return num; } }
Kết quả
Leave a Reply
You must be logged in to post a comment.