还是c语言的问题 麻烦高手帮我看看这个程序哪里出错了

2025-01-02 11:14:38
推荐回答(3个)
回答1:

用二楼的代码,改一个地方
low=0; high=n-1;
=>
low=1; high=n;

回答2:

那就将输入记录的个数传入函数binsearch
int binsearch(RECORD R[],int k, int n);
不过这样好像最后一个记录的位置不对,其他的应该都对了,请高手改改吧。

#include
#define N 100

struct record
{
int key;
int otheritem;
};
typedef struct record RECORD;

RECORD file[N+1];

void insertsort(RECORD R[],int n)
{
int i,j;
for(i=2;i<=n;i++)
{
R[0]=R[i];
j=i-1;
while(R[0].key {
R[j+1]=R[j];
j--;
}
R[j+1]=R[0];
}
}

int binsearch(RECORD R[],int k, int n)
{
int low,mid,high;
low=0;
high=n - 1;
while(low<=high)
{
mid=(low+high)/2;
if(k==R[mid].key)
return mid;
if(k>R[mid].key)
low=mid+1;
else
high=mid-1;
}
return -1;
}

main()
{
int a,j;
int i=1;
int n=0;
RECORD R[N];
printf("Please input the number(input 0 to stop):\n");
scanf("%d",&a);
printf("The record is:\n");
while(a!=0)
{
R[i].key=a;
printf("%6d\n",R[i].key);
n++;
i++;
scanf("%d",&a);
}
printf("\n");
printf("The record now is:\n");
insertsort(R,n);
for(i=1;i<=n;i++)
{
printf("%6d",R[i].key);
}
printf("\n");
printf("Please input the number to be found:\n");
scanf("%6d",&a);
printf("The location of the number be found is:\n");
while(a!=0)
{
j=binsearch(R,a,n);
printf("%6d",j);
printf("\n");
scanf("%6d",&a);
}
return 1;
}

回答3:

#include
#define N 100
struct record
{
int key;
int otheritem;
};
typedef struct record RECORD;
RECORD file[N+1];
void insertsort(RECORD R[],int n)
{
int i,j;
for(i=2;i<=n;i++)
{
R[0]=R[i];
j=i-1;
while(R[0].key{
R[j+1]=R[j];
j--;
}
R[j+1]=R[0];
}
}
int binsearch(RECORD R[],int k)
{
int low,mid,high;
low=0;
high=N-1;
while(low<=high)
{
mid=(low+high)/2;
if(k==R[mid].key)
return mid;
else if(k>R[mid].key)
low=mid+1;
else
high=mid-1;
}
return -1;
}

void main()
{
int a,j;
int i=1;
int n=0;
RECORD R[N];
printf("Please input the number:\n");
scanf("%d",&a);
printf("The record is:\n");
while(a!=0)
{
R[i].key=a;
printf("%6d",R[i].key);
n++;
i++;
scanf("%d",&a);
}
printf("\n");
printf("The record now is:\n");
insertsort(R,n);
for(i=1;i<=n;i++)
{
printf("%6d",R[i].key);
}
printf("\n");
printf("Please input the number to be found:\n");
scanf("%6d",&a);
printf("The location of the number be found is:\n");
while(a!=0)
{
j=binsearch(R,a);
printf("%6d",j);
printf("\n");
scanf("%6d",&a);
}
}