数据结构顺序查找循环输出比对数值存在问题,输出时重复输出且未输出比对数值5?


#include <stdio.h>
#include <malloc.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int keytype;
typedef int infotype;
typedef struct
{
    keytype key;
    infotype otherinfo;
}elemtype;

typedef struct
{
    elemtype *R;
    int length;
}sstable;

int inittable(sstable *st)
{
    st->R=(elemtype*)malloc(11*sizeof(elemtype));
    if(!st->R) 
    return ERROR;
    st->length=0;
    return OK;
}
int search_seq(sstable ST,keytype key)
{
    int i;
    ST.R[0].key = key;
    for(i=ST.length;ST.R[i].key!=key;--i)
        printf("比较数值为:%d\n",ST.R[i].key);
    return i;
}
int main()
 {
     sstable ST;
     inittable(&ST);    
     ST.length=10;
     printf("输入10位数(每输入一次按空格):\n");
     for(int i=1;i<=ST.length;i++)
     {
         printf("输入第%d个:\t",i);
         scanf("%d",&ST.R[i].key);
      } 
      keytype key=5;
     search_seq(ST, key);
     printf("查找到下标为%d:",search_seq(ST,key));
    return 0;
}

image.png

阅读 1.9k
1 个回答
     search_seq(ST, key);
  // ^^^^^^^^^^
     printf("查找到下标为%d:",search_seq(ST,key));
  //                         ^^^^^^^^^^

调用了两次,自然还会输出两次。


    for(i=ST.length;ST.R[i].key!=key;--i)
                            // ^^
        printf("比较数值为:%d\n",ST.R[i].key);

不相等才执行循环体(打印),相等就不执行了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进