我正在通过 C 编程编写代码,并使用 visual studio 编译程序。
我在这里尝试从手动输入的数组元素中查找数字,但它无法正常工作。
#include<stdio.h>
#define SIZE 3
main()
{
int i=0;
int search_no=0;
int myArray[SIZE];
for(i=0;i<SIZE; i++)
{
printf("Enter value : ");
scanf("%d", &myArray[i]);
}
printf("Enter value to search : ");
scanf("%d", &search_no);
for(i=0;i<SIZE;i++)
{
if(search_no==myArray[i])
{
printf("Number found\n");
break;
}
if(search_no!=myArray[i])
{
printf("Unable to find. Kindly re-check the number\n");
break;
}
}
getch();
}
它可以编译,但它没有正确搜索元素,如果我删除 Last IF 语句,它就可以完美运行。无论是否找到值,我都想以两种方式打印消息。
谢谢。
最佳答案
实际上,如果数组中的第一个值不是您要查找的值,您就会退出循环。
将未找到的代码放在循环之后。
int found = 0;
for(i=0;i<SIZE;i++)
{
if(search_no==myArray[i])
{
printf("Number found\n");
found = 1;
break;
}
}
if(found == 0)
{
printf("Unable to find. Kindly re-check the number\n");
}
关于c - 无法使用 IF 语句执行完美搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22187412/