二分查找算法

二分查找算法_第1张图片

1。以所求值和目标值的逐渐逼近:

		if (y < 6 || y>807020306) { cout << "No solution!" << endl; continue; }

		sum = (x * (3 + x * (2 + x * (7 + 8 * x)))) + 6;
		while (fabs(sum - y) > 1e-3)
		{
			if (sum < y)
			{
				min = x;
				x = (max + x) / 2;
			}
			else {
				max = x;
				x = (min + x) / 2;
			}
			sum = (x * (3 + x * (2 + x * (7 + 8 * x)))) + 6;
			if (sum == y) break;
		}printf("%.4lf\n", x);

2.函数对应x的min和max差值的逼近:
 


		cin >> y; 
		// 判断有无解
		if (y < f(0) || y>f(100)) { cout << "No solution!" << endl;  }
		else {
			while (max - min > 1e-7)
			{
				x = (max + min) / 2.0;
				sum = f(x);
				if (sum < y)
					min = x + 1e-7;

				else
					max = x - 1e-7;
				if (sum == y) break;
			}printf("%.4lf\n", (min+max)/2.0);

你可能感兴趣的:(二分查找,算法)