鱼C论坛

 找回密码
 立即注册
查看: 2228|回复: 2

数组类问题

[复制链接]
发表于 2018-6-10 16:58:29 | 显示全部楼层 |阅读模式

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

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

x
从键盘输入一个字符,用折半查找法找出该字符在已排序的字符串a中的位置。若不在a中,则打印该字符不在a中。

#include "stdio.h"
int  main()
{
    char a[12]="abcdsfklmnp", ch;
        int  top, bot, mid;
        printf("input a character   \n");
        scanf("%c", &ch);
        printf("ch = %c\n", ch);
        .............
        if(bot > top)
                printf("该字符不在a中  \n");

        return 0;
}
那路大神来求救一哈。。。。中间的程序怎么写啊
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2018-6-13 22:22:42 | 显示全部楼层
  1. #include <stdio.h>


  2. int  main()
  3. {
  4.     char a[12]="abcdsfklmnp", ch;
  5.     int  top, bot, mid;
  6.    
  7.     printf("input a character   \n");
  8.     scanf("%c", &ch);
  9.    
  10.         printf("ch = %c\n", ch);
  11.    
  12.         top = 10;
  13.         bot = 0;

  14.         while(top >= bot)
  15.         {
  16.                 mid = (top+bot)/2;
  17.                
  18.                 if(a[mid] == ch)
  19.                 {
  20.                         printf("位置: %d\n", mid);
  21.                         break;
  22.                 }
  23.                 else if(a[mid] > ch)
  24.                 {
  25.                         top = mid-1;
  26.                 }
  27.                 else
  28.                 {
  29.                         bot = mid+1;
  30.                 }
  31.         }

  32.         if(bot > top)
  33.                 printf("该字符不在a中  \n");

  34.         return 0;
  35. }
复制代码


想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-6-13 22:43:18 | 显示全部楼层


你的字符串没有排序,s不应该出现在那个位置,我给改为e了
  1. #include "stdio.h"
  2. int  main()
  3. {
  4.     char a[12]="abcdefklmnp", ch;
  5.         int  top, bot, mid;
  6.         printf("input a character   \n");
  7.         scanf("%c", &ch);
  8.         printf("ch = %c\n", ch);
  9.         bot = 0;
  10.         top = 10;
  11.         
  12.         while(bot <= top)
  13.         {
  14.                 mid = ( bot + top ) / 2;
  15.                 if(a[mid] == ch)
  16.                 {
  17.                         printf("%d", mid);
  18.                         return 0;
  19.                         }
  20.                         else if(a[mid] > ch)
  21.                         {
  22.                                 top = mid - 1;
  23.                         }
  24.                         else
  25.                         {
  26.                                 bot = mid + 1;
  27.                         }
  28.                 }
  29.         if(bot > top)
  30.                 printf("该字符不在a中  \n");

  31.         return 0;
  32. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-3-29 13:17

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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