【发布时间】:2013-10-06 00:09:04
【问题描述】:
我尝试编写一个程序,该程序将文本文件作为输入,然后使用用户输入进行二进制搜索。问题是,当我编译并运行它时,程序会自动退出并退出,并且不允许用户输入。
我怀疑它仍在以某种方式读取数据文件,但它应该已经没有选项了。有什么想法吗?
代码:
#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.
【问题讨论】:
-
你在哪里打开了文本文件?key的值是多少?你为什么用
printf("\nDo you want to search for an integer? (y/n) "); scanf("%c", &search);? -
投票结束。 OP 正在询问文件处理,但在提供的代码中没有类似的内容。
-
我们可能会假设他所指的“文件”是标准输入,也许程序(旨在)从终端或通过命令行重定向提供的文件工作。
-
使用示例命令条目编辑。
-
请注意,a)您的代码要求输入 y/n,如果答案是“y”,则立即再次要求输入 y/n,并且 b)从不问“输入整数:”这个问题您的示例输出暗示并且 c) 从标准输入读取问题的答案,在您的示例输出中,标准输入被重定向到 data.txt,但您的示例输出暗示问题是从终端读取的,而不是 (stdin) 文件。 stdin 可以是键盘或重定向文件,但显然不能同时是两者...