数组类问题
从键盘输入一个字符,用折半查找法找出该字符在已排序的字符串a中的位置。若不在a中,则打印该字符不在a中。#include "stdio.h"
intmain()
{
char a="abcdsfklmnp", ch;
inttop, bot, mid;
printf("input a character \n");
scanf("%c", &ch);
printf("ch = %c\n", ch);
.............
if(bot > top)
printf("该字符不在a中\n");
return 0;
}
那路大神来求救一哈。。。。中间的程序怎么写啊
#include <stdio.h>
intmain()
{
char a="abcdsfklmnp", ch;
inttop, bot, mid;
printf("input a character \n");
scanf("%c", &ch);
printf("ch = %c\n", ch);
top = 10;
bot = 0;
while(top >= bot)
{
mid = (top+bot)/2;
if(a == ch)
{
printf("位置: %d\n", mid);
break;
}
else if(a > ch)
{
top = mid-1;
}
else
{
bot = mid+1;
}
}
if(bot > top)
printf("该字符不在a中\n");
return 0;
}
粉红猪小妹 发表于 2018-6-13 22:22
你的字符串没有排序,s不应该出现在那个位置,我给改为e了
#include "stdio.h"
intmain()
{
char a="abcdefklmnp", ch;
inttop, bot, mid;
printf("input a character \n");
scanf("%c", &ch);
printf("ch = %c\n", ch);
bot = 0;
top = 10;
while(bot <= top)
{
mid = ( bot + top ) / 2;
if(a == ch)
{
printf("%d", mid);
return 0;
}
else if(a > ch)
{
top = mid - 1;
}
else
{
bot = mid + 1;
}
}
if(bot > top)
printf("该字符不在a中\n");
return 0;
}
页:
[1]