欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

二分查找算法——Java版

程序员文章站 2024-03-20 17:36:46
...

这是将网上的C++版的改写成Java的

理论上把函数f()改一下就可以计算任意方程的0点。

仅供参考,可以将其写成递归的。

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ErFenFa {

	static int m;
	static double x1, x2, x3;

	public static double f(double x) {
		double y;
		y = x * x * x - x - 1;
		return y;
	}

	public static void main(String[] args) throws NumberFormatException,
			IOException {
		double a, b;
		System.out.println("please input two number a,b");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		a = Double.valueOf(br.readLine());
		b = Double.valueOf(br.readLine());

		double x1 = a;
		double x2 = b;
		double x3;

		for (int i = 1;; i++) {
			if (f(x1) == 0) {
				m = (int) (x1 * 100);
				x1 = m / 100;
				System.out.println("方程的根是x=" + x1 + ",迭代次数=" + i);
			}
			if (f(x2) == 0) {
				m = (int) (x2 * 100);
				x2 = m / 100;
				System.out.println("方程的根是x=" + x2 + ",迭代次数=" + i);
			}
			if (f(x1) * f(x2) > 0) {
				System.out.println("方程无解!" + ",迭代次数=" + i);
				return;
			} else if (f(x1) * f(x2) < 0) {
				x3 = (x1 + x2) / 2; // return 1;

				if (f(x3) == 0) {
					m = (int) (x3 * 100);
					x3 = m / 100;
					System.out.println("方程的根是x=" + x3 + ",迭代次数=" + i);
				}
				if (f(x3) * f(x1) < 0) {
					x2 = x3;
					if (Math.abs(x1 - x3) < 0.00001) {
						m = (int) (x2 * 100);
						x2 = m / 100;
						System.out.println("方程的根是x=" + x2 + ",迭代次数=" + i);
						break;
					}
				}
				if (f(x3) * f(x2) < 0) {
					x1 = x3;// f(x3)*f(x2)
					if (Math.abs(x2 - x3) < 0.00001) {
						m = (int) (x1 * 100);
						x1 = m / 100;
						System.out.println("方程的根是x=" + x1 + ",迭代次数=" + i);
						break;
					}

				}
			}
		}
	}

}