鱼C论坛

 找回密码
 立即注册
查看: 2159|回复: 1

C语言

[复制链接]
发表于 2020-4-3 10:17:33 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
题目要求:有15个已经排序号的数存放在一个数组中,输入一个数,要求用折半查找法找出该数是数组中第几个元素的值。如果该数不在数组中,则输出无此数。


变量说明:top,bott为查找区间两端点的下标;loca为查找成功与否的开关变量。


这段代码哪里错了,为什么输出异常?

  1. #include<stdio.h>

  2. int main()
  3. {
  4.     int N,number;
  5.     int top,bott,min,loca;
  6.     int a[15] = {-3,-1,0,1,2,4,6,7,8,9,12,19,21,23,50};

  7.     printf("Input the number to be found:");
  8.     scanf("%d",&number);

  9.     loca = 0;
  10.     top = 0;
  11.     bott = N-1;

  12.     if((number < a[0]) || (number > a[N-1]))
  13.     {
  14.         loca = -1;
  15.     }

  16.     while((loca == 0)&&(top <= bott))
  17.     {
  18.         min = (top + bott)/2;
  19.         if(number == a[min])
  20.         {
  21.             loca = min;
  22.             printf("The serial number is %d. \n",loca+1);
  23.         }
  24.         else if(number < a[min])
  25.         {
  26.             bott = min - 1;
  27.         }
  28.         else
  29.         {
  30.             top = min + 1;
  31.         }
  32.     }
  33.     if(top > bott)
  34.     {
  35.         printf("%d isn't in tabel\n",number);
  36.     }
  37. }
复制代码


小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-4-3 10:32:18 | 显示全部楼层
N没有赋初值
  1.   N = sizeof(a) / sizeof(int);
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-5 08:28

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表