为什么我的二进制搜索程序中没有输出? [英] Why there is no output in my Binary Search program?

查看:67
本文介绍了为什么我的二进制搜索程序中没有输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//这里是代码,没有输出。

//我是入门级学生,所以请帮帮我。

//在这里,我试图计算二进制搜索程序中的迭代次数。

//here is the code, there is no output.
//I am an entry level student to this, so please help me out.
//here I am trying to count the number of iterations in a binary search program.

#include<stdio.h>
int main()
{ int array[10]={2,10,44,55,66,78,87,89,90},m,left,right,key=90,counter;
  left=0;
  right=8;
  while(left<=right)
  { m=(left+right)/2;
    if(key==array[m])
        {counter++; return 1;}
    else if(key>array[m])
        {counter++; left=m+1;}
    else
        {counter++; right=m-1;}
  }
printf("the number of iterations are %d",counter);
return 0;

}

推荐答案

因为您的实施不正确。尝试:

Because your implementation is not correct. Try:
#include<stdio.h>
int main()
{
  int array[]={2,10,44,55,66,78,87,89,90},m,left,right,key=90,counter=0;
  left=0;
  right=sizeof(array)/sizeof(array[0]) -1;

  while(left <= right)
  {
    m=(left+right)/2;
    counter++;
    if(key == array[m])
      break;
    else if(key>array[m])
      left = m + 1;
    else
      right=m-1;
  }
  printf("the number of iterations are %d\n",counter);
  if ( key == array[m])
    printf("the item was found at index %d\n", m);

  return 0;

}


你在开玩笑;-)

程序结束于返回1;

你可以使用break语句。





提示:



1.在一行上的每个语句。甚至是int

的声明2.在一行上的每个括号。

3.使用调试器单步模式



原因:当代码变得更多时代码保持清洁和可读。
you are kidding ;-)
the program is ending by "return 1;
you can use the break statement.


tips:

1. every statement on ONE line. even a declarations of int
2. every bracket on ONE line.
3. use the debugger in single step mode

Reason: the code stays cleaner and readble when it gets more.


这篇关于为什么我的二进制搜索程序中没有输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆