为什么它会跳到'else`部分?

时间:2013-03-02 13:00:56

标签: c

我刚试过这个linear search,结果显示它显示else部分。我不知道我做错了什么。逻辑......

#include<stdio.h>
#include<conio.h>
main()
{
      int a[10], i, x, size;
      printf("Enter the size of the array: \n");
      scanf("%d",&size);
      printf("Enter the elements into the array: \n");
      for(i=0; i<size; i++)
      {
               scanf("%d",&a[i]);
      }
      printf("Enter the element to be searched for: \n");
      scanf("%d",&x);
      for(i=0; i<size; i++)
      {
               if(x==a[i])
               {
                   printf("The element is at: %d",i);
                   break;
               }
               else
               {
                   printf("The element is not in the array.");
                   break;
               }
      }
getch();
}

6 个答案:

答案 0 :(得分:3)

因为当它检查第一个元素并且看到它不是您正在寻找的那个时,它会退出循环。

答案 1 :(得分:2)

breakif语句中都有else,这意味着您没有遍历数组但总是在第一个元素后面出for循环

答案 2 :(得分:1)

  1. 你只需要遍历数组,并且对于每个元素,你知道它是否是元素,并且在每种情况下你都决定它是否是全局的。这是不正确的。让我们声明一个布尔变量,在开头设置为false,如果找到该元素,则将varibale设置为true;最后,如果此变量为false,则使用搜索编写未成功的消息,而不是在每个元素之后。只有在成功之后才能休息。

  2. 您必须检查,该尺寸小于数组a的尺寸;

答案 3 :(得分:1)

break部分删除else声明 -
你的代码只检查第一个数组元素是否是要搜索的元素

使用以下内容更好地修改循环:

    int flag = 0;
    for(i=0; i<size; i++)
    {
        if(x==a[i])
        {
            printf("The element is at: %d",i);
            break;
        }
        else
        {           
            flag = 1;  
        }
    }

    //will print if number is not present in the array
    if(flag !=0 ){
        printf("The element is not in the array.");
    }

答案 4 :(得分:1)

将搜索循环更改为:

  int found = 0;

  i=0;
  while(found == 0 && i < size){
    if(x == a[i]){
        found = 1;
        printf("The element is at: %d",i);
        break;  
    }
    i++;
  }
  if(found == 0)
    printf("The element is not in the array.");

答案 5 :(得分:0)

这是一种没有旗帜就可以做到的方法!

在循环完成后,您需要对数组中的not进行检查,而不是在它仍在其中时进行检查。

      for(i=0; i<size; i++)
      {
               if(x==a[i])
               {
                   printf("The element is at: %d",i);
                   i = size + 2;
               }
      }

      if (i <= size)
      {
          printf("The element is not in the array.");
      }