给定代码的输出应该是数组中元素的索引号,但我没有得到预期的输出。
这是我的代码:
int main() {
int n, a, b;
int arr[100];
cout << "Enter the size of array";
cin >> n;
cout << "Enter the number to find";
cin >> a;
cout << "Enter elements in array";
for (int i = 0; i < n; i++)
cin >> arr[n];
for (int i = 0; i < n; i++) {
if (arr[n] == a) {
cout << n;
} else
n++;
}
return 0;
}
最佳答案
这里:
if(arr[n]==a)
您需要使用 i
:
if(arr[i]==a)
完整 else
-案例是多余的;去掉它。此外,您必须确保 n <= 100
,否则你有一个安全漏洞(缓冲区溢出)。
使用 std::size_t
而不是 int
用于数组索引。
关于c++ - 如何解决C++中的线性搜索问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54663374/