我的布尔函数在找到“ needle”时应返回true,但即使返回false并打印出“找不到针” 我尝试使用GDB进行调试,事实证明它实际上返回true,但之后又返回false,而在满足条件后不会中断??
这是我的代码:
int FindMidPoint(int array[],int size)
{
int i = size / 2;
int Midpoint = array[i];
return Midpoint;
}
bool search(int value, int array[], int n)
{
// TODO: implement a searching algorithm
if ( n <= 0 )
return false;
int Midpoint = FindMidPoint(array,n);
int mid = n / 2;
int x = round(mid);
int *firsthalf = malloc((x) * sizeof(int));
int *secondhalf = malloc((x) * sizeof(int));
memcpy(firsthalf,array, x * sizeof(int));
memcpy(secondhalf,array + x, x * sizeof(int));
if (value == Midpoint)
{
return true;
}
else if (value > Midpoint)
{
search (value,secondhalf,mid);
}
else if (value < Midpoint)
{
search(value,firsthalf,mid);
}
return false;
}
这是GDB给我的:
Starting program: /root/cs50/pset3/hacker3/find/find 10
haystack[0] = 10
haystack[1] = 12
haystack[2] = 14
haystack[3] = 6
haystack[4] = 8
haystack[5] = 20
haystack[6] = 200
haystack[7] = 2000
haystack[8] = 202
haystack[9] =
6
8
10
12
14
20
200
202
2000
Breakpoint 1, search (value=10, array=0x7ffffffbe100, n=9) at
helpers.c:32
32 if ( n <= 0 )
(gdb) n
35 int Midpoint = FindMidPoint(array,n);
(gdb) n
36 int mid = n / 2;
(gdb) n
37 int x = round(mid);
(gdb) n
38 int *firsthalf = malloc((x) * sizeof(int));
(gdb) n
39 int *secondhalf = malloc((x) * sizeof(int));
(gdb) n
40 memcpy(firsthalf,array, x * sizeof(int));
(gdb) n
41 memcpy(secondhalf,array + x, x * sizeof(int));
(gdb) n
43 if (value < Midpoint)
(gdb) n
45 search(value,firsthalf,mid);
(gdb) n
Breakpoint 1, search (value=10, array=0x405850, n=4) at helpers.c:32
32 if ( n <= 0 )
(gdb) n
35 int Midpoint = FindMidPoint(array,n);
(gdb) n
36 int mid = n / 2;
(gdb) n
37 int x = round(mid);
(gdb) n
38 int *firsthalf = malloc((x) * sizeof(int));
(gdb) n
39 int *secondhalf = malloc((x) * sizeof(int));
(gdb) n
40 memcpy(firsthalf,array, x * sizeof(int));
(gdb) n
41 memcpy(secondhalf,array + x, x * sizeof(int));
(gdb) n
43 if (value < Midpoint)
(gdb) info locals
Midpoint = 10
mid = 2
x = 2
firsthalf = 0x405890
secondhalf = 0x4058b0
(gdb) n
47 else if (value > Midpoint)
(gdb) info locals
Midpoint = 10
mid = 2
x = 2
firsthalf = 0x405890
secondhalf = 0x4058b0
(gdb) n
52 else if (value == Midpoint)
(gdb) n
54 return true;
(gdb) n
64 }
(gdb) n
search (value=10, array=0x7ffffffbe100, n=9) at helpers.c:46
46 }
(gdb) n
62 return false;
(gdb) n
64 }
(gdb)
main (argc=2, argv=0x7fffffffe238) at find.c:69
69 printf("\nDidn't find needle in haystack.\n\n");
(gdb)
Didn't find needle in haystack.
70 return 1;
我不知道我的代码有什么问题,或者我不了解布尔函数,请帮忙!
答案 0 :(得分:2)
只有在第一次调用时满足以下条件,search
函数才会返回true
:
value == Midpoint
进行所有递归调用,但其结果被忽略,并且始终返回false
:
else if (value > Midpoint)
{
search(value,secondhalf,mid);
}
else if (value < Midpoint)
{
search(value,firsthalf,mid);
}
return false;
您需要从递归返回结果:
else if (value > Midpoint)
{
return search(value,secondhalf,mid);
}
else if (value < Midpoint)
{
return search(value,firsthalf,mid);
}
return false;