[英]How to solve linear search problem in c++?
The output of the given code should be the index number of element that is in array but i am not getting the expected output. 给定代码的输出应该是数组中元素的索引号,但是我没有得到预期的输出。
Here is my code: 这是我的代码:
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;
}
Here: 这里:
if(arr[n]==a)
You need to use i
: 您需要使用i
:
if(arr[i]==a)
The complete else
-case is superfluous; 完整的else
-case是多余的; remove it. 去掉它。 Also, you have to make sure that n <= 100
, or else you have a security hole (buffer overflow). 另外,您必须确保n <= 100
,否则将有安全漏洞(缓冲区溢出)。 Use std::size_t
instead of int
for array indices. 为数组索引使用std::size_t
而不是int
。
You using 'n; 您使用'n; as array index to take input and match search element. 作为数组索引以获取输入并匹配搜索元素。 It should be 'i' instead of 'n'. 它应该是“ i”而不是“ n”。
#include <iostream>
using namespace std;
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[i];
for(int i=0;i<n;i++){
if(arr[i]==a)
{
cout<<i<< "";
}
}
return 0;
}
as @Erlkoenig said: 正如@Erlkoenig所说:
"You need to use i: “您需要使用i:
if(arr[i]==a)
The complete else-case is superfluous; if(arr[i]==a)
完整的else-case是多余的; remove it. 去掉它。 Also, you have to make sure that n <= 100, or else you have a security hole (buffer overflow). 另外,您必须确保n <= 100,否则您有安全漏洞(缓冲区溢出)。 Use std::size_t instead
of int
for array indices." 使用std::size_t instead
int
作为数组索引。”
Also n++
will propably give you a segmentation fault (depending no the starting n and how quickly you will find the "number to find". I'm pretty sure that if the number is not in the array you will get a sgementation fault. 同样, n++
可能会给您带来分段错误(不依赖于起始n以及您将以多快的速度找到“要查找的数字”。我很确定,如果数字不在数组中,则会出现sgementation错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.