//二分查找法//
# include<stdio.h>
void main()
{
int a[16],i,num,flag=0,top,bottom,mid
//定义一个一维数组a[16]用来存放供查找用的数据,但只用a[1]——a[15]//
//num用来放要查找的数据,flag是表示是否找到的开关变量,top表示查找的起始位置,bottom表示查找的终止位置,mid表示top与bottom的中间位置//
char goon
//变量goon为'y'或'Y'时表示继续下一轮查找,否则终止程序//
printf("请输入第1个数字:\n")
scanf(" %d",&a[1])
//依次输入第二到第十五个数,并要求输入的数递减//
for(i=2i<=15i++)
{
printf("请输入第%d个数字:\n",i)
scanf(" %d",&a[i])
if(a[i]>=a[i-1])
{
printf("请再次输入,它应该比上一个数小:\n")
scanf(" %d",&a[i])
}
}
//输出刚才输入的数//
printf("你刚才输入的数是:\n")
for(i=1i<=15i++)
printf(" %d",a[i])
printf("\n")
//查找循环开始//
do
{
printf("现在请输入你要查找的数:\n")//输入想要查找的数//
scanf(" %d",&num)
top=15
bottom=1
mid=15/2+1
if(num>a[1] || num<a[15])//如果要查找的数据不在规定范围内,令flag=1,输出超出范围的信息//
{
flag=1
printf("你所要查找的数字不在范围内!\n")
}
while(flag==0 &&(top-bottom)>0)//如果在规定的范围内,开始二分法查找//
{
if(num==a[mid])//找到所需数据,退出本层循环//
{
printf("你所要查找的数字是第%d个。\n",mid)
flag=1
}
else if(num>a[mid])//如果要查找的数据比a[mid]大,在前半数组查找//
{
top=mid+1
mid=(top+bottom)/2
}
else //如果要查找的数据比a[mid]小,在后半数组查找//
{
bottom=mid-1
mid=(top+bottom)/2
}
}
if(flag==0)//如果未找到数据,输出找不到的信息//
printf("无法找到你要找的数字!\n")
printf("是否继续查找?(Y/N):\n")//询问是否开始下一轮查找//
scanf(" %c",&goon)
}while(goon=='y' || goon=='Y')
}
#include <stdio.h>#include <math.h>
float getvalue(float x)
{
return x*x*x+4*x*x-10
}
void main()
{
float a=1,b=1.5,c
c=(a+b)/2
while(fabs(getvalue(c))>0.00001 &&fabs(a-b)>0.00001){
if(getvalue(c)*getvalue(b)<0) a=c
if(getvalue(a)*getvalue(c)<0) b=c
c=(a+b)/2
}
printf("%0.3f\n",c)
}
#include <stdio.h>#include <math.h>
void main()
{int x1,x2,x,f1,f2
f1=x1*x1*x1-3*x1*x1-2*x1-6
f2=x2*x2*x2-3*x2*x2-2*x2-6
do
{scanf("%d%d",x1,x2)
}while(f1*f2>0)
do
{x=(x1+x2)/2
f=x*x*x-3*x*x-2*x-6
if(f*f1<0)
{x2=x
f2=f}
if(f*f2<0)
{x1=x
f1=f}
}while(fabs(x1-x2)>0.001)
printf("%d",x)}