我使用布尔运算符错了吗?
Am I using the boolean operator wrong?
我正在尝试查看数组以查看是否在其中找到了精确的元素 (x)。
为此,我在问题的开头说 contor=0(布尔参数),这意味着数组中没有 x,但是如果 for 循环正在运行并且在数组中找到 x,我说contor=1 ... 最后我做了 if(contor) else 测试,但在数组中找不到 x 的情况下它不起作用。它只是没有显示任何东西。我不明白...我是初学者。谢谢!
#include<iostream>
using namespace std;
void main()
{int x, st, dr, m,n,i,contor=0; //dr = right, st = left, m=middle;
int v[100];
cout << "How many elements will the array have?";
cin >> n;
cout << endl;
for (i = 0; i < n;i++)
{cout << "Insert a element in the array:";
cin >> v[i];
}
cout << "Which is the number you are looking for?";
cin >> x;
st = 0;
dr = n - 1;
for (i = st; i <= dr;)
{m = (st + dr) / 2;
if (v[m] == x)
{ contor = 1;
break;
}
else if (v[m] > x)
dr = m - 1;
else st = m + 1;
}
if (contor)
cout << "The element you are looking for is in the array.";
else
cout << "The element you are looking for is NOT in the array.";
cin.get();
cin.get();
}
您正在尝试进行二分查找,但您是在无限循环中进行的。如果找到该元素,您将退出循环,但如果找不到,您的循环将无休止地继续下去。此外,您尝试在不保证有序的数组中进行二分查找。假设数组是有序的,也就是说:
i <= j <=> v[i] <= v[j]
这是可行的方法:
do {
m = (st + dr) / 2;
if (v[m] == x) {
contor = 1;
break;
} else if (v[m] > x) {
dr = (st + m - 1) / 2;
} else {
st = (m + dr + 1) / 2;
}
} while (st < dr);
我正在尝试查看数组以查看是否在其中找到了精确的元素 (x)。 为此,我在问题的开头说 contor=0(布尔参数),这意味着数组中没有 x,但是如果 for 循环正在运行并且在数组中找到 x,我说contor=1 ... 最后我做了 if(contor) else 测试,但在数组中找不到 x 的情况下它不起作用。它只是没有显示任何东西。我不明白...我是初学者。谢谢!
#include<iostream>
using namespace std;
void main()
{int x, st, dr, m,n,i,contor=0; //dr = right, st = left, m=middle;
int v[100];
cout << "How many elements will the array have?";
cin >> n;
cout << endl;
for (i = 0; i < n;i++)
{cout << "Insert a element in the array:";
cin >> v[i];
}
cout << "Which is the number you are looking for?";
cin >> x;
st = 0;
dr = n - 1;
for (i = st; i <= dr;)
{m = (st + dr) / 2;
if (v[m] == x)
{ contor = 1;
break;
}
else if (v[m] > x)
dr = m - 1;
else st = m + 1;
}
if (contor)
cout << "The element you are looking for is in the array.";
else
cout << "The element you are looking for is NOT in the array.";
cin.get();
cin.get();
}
您正在尝试进行二分查找,但您是在无限循环中进行的。如果找到该元素,您将退出循环,但如果找不到,您的循环将无休止地继续下去。此外,您尝试在不保证有序的数组中进行二分查找。假设数组是有序的,也就是说:
i <= j <=> v[i] <= v[j]
这是可行的方法:
do {
m = (st + dr) / 2;
if (v[m] == x) {
contor = 1;
break;
} else if (v[m] > x) {
dr = (st + m - 1) / 2;
} else {
st = (m + dr + 1) / 2;
}
} while (st < dr);