分别用C语言和matlab实现二分法查找数据

从形式上能够发现区别是,matlab是一句一句编译的,而c语言是对一个完整的代码段进行编译的,并且c中有头文件(#include(...)),而matlab中没有,对于数值运算matlab是很简便强大的,c就有点繁琐,对于算法要求c相对更高点。

 

具体例子如下:

C语言

#define M 10

#include<stdio.h>

void main()
{
static int a[M]={-12,0,6,16,23,56,80,100,110,115};
int n, low, mid, high, found;
low=0;
high=M-1;
found=0;
printf("Input a number to be searched:");
scanf("%d", &n);
while(low<=high)
{
mid=(low+high)/2;
if (n==a[mid])
{
found = 1; break;
}/*找到,结束循环*/
else if (n > a[mid])
low=mid+1;
else
high=mid-1; }
if (found==1)
printf("The index of %d is %d",n,mid);
else
printf("There is not %d",n); }

 

 

mtalab实现程序如下:

 x=fix(100*rand);
  n=7;
  test=1;
  for k=1:7
numb=int2str(n);
disp(\'a guess is a number between 0 and 100\')
guess=input(\':\');
if guess<x
disp(\'low\')
elseif guess>x
disp(\'high\')
else disp(\'you win\')
test=0;
break;
end
n=n-1;
end
if test==1
disp(\'you lost\')