c++ - 如何解决C++中的线性搜索问题?

标签 c++ arrays algorithm

给定代码的输出应该是数组中元素的索引号,但我没有得到预期的输出。

这是我的代码:

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/

相关文章:

c++ - 其他进程在 MPI_Sendrecv 之后挂起

c++ - 在 C++ 中修改单个字符串元素

algorithm - 最大积子数组

c++ - 在编译时获取静态 constexpr 数组的最小值/最大值

c++ - siginfo_t 尚未声明 : caused by inclusion of a thrift header

javascript - 从现有数组属性创建新数组

algorithm - 足迹查找算法

multithreading - 了解分配 : Search for prime number above 1 quadrillion using servlets

c++ - 如何在 Visual Studio 中从 Qt Foo.ui 生成 ui_Foo.h 文件?

c++ - 我收到 [Error] 'Eintrag' does not name a type 我不知道为什么