在 while 条件本身内实现一个中断 while 的 if 条件
Implementing an if condition that breaks the while, inside the while condition itself
我有这部分代码:
int arrayBinary_search(int myarray[], int key){
int selector;
int low_limit = 0;
int high_limit = SIZE;
while (1){
selector = (low_limit+high_limit)/2;
printf("The selector is: %d\n", selector);
if (myarray[selector] == key){
return 1;
}
else {
if (low_limit==selector || high_limit==selector)
break;
if (key < myarray[selector])
high_limit = selector;
else
low_limit = selector;
printf("The high_limit is: %d\n", high_limit);
printf("The low_limit is: %d\n", low_limit);
}
}
}
此代码在数组中进行二进制搜索。它有效,但 while(1)
不好看。我想实施一些条件来暂时替换那个“1”。条件是如果在 while 循环内,那会打破它。我试过: while (!(low_limit==selector) && !(high_limit==selector))
但它在第一个循环后停止,因为在第一个循环后, "selector" 具有与 "high_limit".
相同的值
完整代码here.
您可以使用 do-while
键匹配时退出的循环:
int arrayBinary_search(int myarray[], int key)
{
int selector;
int low_limit = 0;
int high_limit = SIZE;
do {
selector = (low_limit + high_limit) / 2;
printf("The selector is: %d\n", selector);
if (low_limit == selector || high_limit == selector)
return 0;
if (key < myarray[selector])
high_limit = selector;
else
low_limit = selector;
printf("The high_limit is: %d\n", high_limit);
printf("The low_limit is: %d\n", low_limit);
} while (myarray[selector] != key);
return 1;
}
另一方面,arrayGenerator
函数没有 return 和 int
,您也不需要它,您应该 void
.
我有这部分代码:
int arrayBinary_search(int myarray[], int key){
int selector;
int low_limit = 0;
int high_limit = SIZE;
while (1){
selector = (low_limit+high_limit)/2;
printf("The selector is: %d\n", selector);
if (myarray[selector] == key){
return 1;
}
else {
if (low_limit==selector || high_limit==selector)
break;
if (key < myarray[selector])
high_limit = selector;
else
low_limit = selector;
printf("The high_limit is: %d\n", high_limit);
printf("The low_limit is: %d\n", low_limit);
}
}
}
此代码在数组中进行二进制搜索。它有效,但 while(1)
不好看。我想实施一些条件来暂时替换那个“1”。条件是如果在 while 循环内,那会打破它。我试过: while (!(low_limit==selector) && !(high_limit==selector))
但它在第一个循环后停止,因为在第一个循环后, "selector" 具有与 "high_limit".
完整代码here.
您可以使用 do-while
键匹配时退出的循环:
int arrayBinary_search(int myarray[], int key)
{
int selector;
int low_limit = 0;
int high_limit = SIZE;
do {
selector = (low_limit + high_limit) / 2;
printf("The selector is: %d\n", selector);
if (low_limit == selector || high_limit == selector)
return 0;
if (key < myarray[selector])
high_limit = selector;
else
low_limit = selector;
printf("The high_limit is: %d\n", high_limit);
printf("The low_limit is: %d\n", low_limit);
} while (myarray[selector] != key);
return 1;
}
另一方面,arrayGenerator
函数没有 return 和 int
,您也不需要它,您应该 void
.