我试图编写一个程序,它将文本文件作为输入,然后使用用户输入进行二进制搜索。问题是,当我编译并运行它时,程序会自动退出并退出,并且不允许用户输入。
我怀疑它仍在以某种方式读取数据文件,但它应该已经没有选项了。有任何想法吗?
编码:
#include <stdio.h>
#include <stdarg.h>
int A[100];
char search;
int i, key, len, imin, imax, KEY_NOT_FOUND;
int result;
main() {
// Scan in array length.
scanf("%d", &len);
// Scan in array integers.
for(i = 0; i < len; i++) {
scanf("%d", &A[i]);
}
imin = 0;
imax = len - 1;
printf("Welcome to Binary Search!");
printf("\nDo you want to search for an integer? (y/n) ");
scanf("%c", &search);
while(search == 'y') {
printf("\nDo you want to search for an integer? (y/n) ");
scanf("%c", &search);
result = binary_search(*A, key, imin, imax);
printf("\n%d", result);
}
}
int binary_search(int *A, int key, int imin, int imax) {
// Test if array is empty
if(imax < imin)
// Set is empty, so return value showing not found.
return KEY_NOT_FOUND;
else {
// Calculate midpoint to cut set in half
int imid = midpoint(imin, imax);
// Three-way comparison
if(A[imid] > key)
// Key is in lower subset.
return binary_search(A, key, imin, imid - 1);
else if(A[imid] < key)
// Key is in upper subset.
return binary_search(A, key, imid + 1, imax);
else
// Key has been found.
return imid;
}
}
int midpoint(int imin, int imax) {
int imid = imax / 2;
return imid;
}
这是文本文件:
10
-144 -1 0 10 75 233 341 1000 8192 57885161
示例命令条目:
a.out < data.txt
样本输出:
Welcome to Binary Search!
Do you want to search for an integer? (y/n) y
Enter the Integer: 341
341 Found!
Do you want to search for an integer? (y/n) n
The End!
已编辑,因为答案没有考虑到问题。代码不打印 n found yet。