英文:
Why curly braces for loop and if give wrong output in linear search in C?
问题
当我使用这个函数时,即使数组中有元素,它仍然返回-1。
int linear_search(int arr[], int length, int target)
{
for (int i=0; i < length; i++) {
if (arr[i] == target){
return i;
}
}
return -1;
}
然后我移除了花括号,它就正常工作了。
int linear_search(int arr[], int length, int target)
{
for (int i=0; i < length; i++)
if (arr[i] == target)
return i;
return -1;
}
英文:
When I used this function, it return -1 even if element of array was there.
int linear_search(int arr[], int length, int target)
{
for (int i=0; i < n; i++) {
if (arr[i] == target){
return i;}
return -1;
}
}
I then removed curly braces and it worked
int linear_search(int arr[], int length, int target)
{
for (int i=0; i < n; i++)
if (arr[i] == target)
return i;
return -1;
}
答案1
得分: 1
The first function would return -1 on the first iteration if arr[i] != target
because a return
statement follows the if
statement inside the loop.
Aside: I couldn't see the hidden braces at first. Consider adopting one of the following formatting styles:
#if 0
for (int i=0; i < n; i++) {
if (arr[i] == target){
return i;}
#else
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
return i;
}
}
// Or:
for (int i = 0; i < n; i++)
{
if (arr[i] == target)
{
return i;
}
}
#endif
英文:
The first function would return -1 on the first iteration if arr[i] != target
because a return
statement follows the if
statement inside the loop.
Aside: I couldn't see the hidden braces at first. Consider adopting one of the following formatting styles:
#if 0
for (int i=0; i < n; i++) {
if (arr[i] == target){
return i;}
#else
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
return i;
}
}
// Or:
for (int i = 0; i < n; i++)
{
if (arr[i] == target)
{
return i;
}
}
#endif
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论