用C语言来编进退法的搜索区间的源代码如下:
#include<stdio.h>
void main()
{
int a[20],x,i,start,end
printf("input 20 numbers:\n")
for(i=0i<20i++) scanf("%d",&a[i])
printf("please enter the number:\n")
scanf("%d",&x)
for(start=0,end=19start<=end)
{
i=start+(end-start)/2
if (x==a[i])
{
printf("%d",i+1)
getch()
return
}
else if (x>a[i]) end = i-1
else start=i+1
}
扩展资料
1、C语言查找是在大量的信息中寻找一个特定的信息元素,在计算机应用中,查找是常用的基本运算,例如编译程序中符号表的查找。
2、其实二分查找、插值查找以及斐波那契查找都可以归为一类——插值查找。插值查找和斐波那契查找是在二分查找的基础上的优化查找算法。
用二分法求f(x)=x^3-2*x-5=0,搜索区间为〔2,3),计算精度要求≤10-7.C程序设计如下:
#include<stdio.h>
#include<math.h>
void main()
{
float x0, x1,x2,fx0,fx1,fx2
do
{
printf("Enter x1&x2:")
/*输入区间(x1,x2)的端值x1,x2即x1=2,x2=3*/
scanf("%f,%f",&x1,&x2)
fx1=x1*((x1-0)*x1-2)-5
fx2=x2*((x2-0)*x2-2)-5
}
while(fx1*fx2>0)
do
{
x0=(x1+x2)/2
fx0=x0*((x0-0)*x0-2)-5
if((fx0*fx1)<0)
{x2=x0
fx2=fx0
}
else
{x1=x0
fx1=fx0
}
while(fabs(fx0)>=1e-7)
printf("x=%6.2f\n",x0)
}
C++程序设计如下:
#include<iostream.h>
#include<math.h>
void main()
{
float x0, x1,x2,fx0,fx1,fx2
do
{
cout<<"Please enter x1&x2:"<<endl
//输入区间(x1,x2)的端值x1,x2即x1=2,x2=3
cin>>x1>>x2
fx1=x1*((x1-0)*x1-2)-5
fx2=x2*((x2-0)*x2-2)-5
}
while(fx1*fx2>0)
do
{
x0=(x1+x2)/2
fx0=x0*((x0-0)*x0-2)-5
if((fx0*fx1)<0)
{x2=x0
fx2=fx0
}
else
{x1=x0
fx1=fx0
}
while(fabs(fx0)>=1e-7)
cout<<"x为"<<x0<<endl
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)