【问题标题】:How to solve linear search problem in c++?如何解决 C++ 中的线性搜索问题?
【发布时间】:2019-02-13 05:48:12
【问题描述】:

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

这是我的代码:

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;
}

【问题讨论】:

  • 你应该一次又一次地调试你的代码!之后就可以发帖了!你当然不是新手!!

标签: c++ arrays algorithm


【解决方案1】:

这里:

if(arr[n]==a)

你需要使用i:

if(arr[i]==a)

完整的else-case 是多余的;去掉它。此外,您必须确保n &lt;= 100,否则您有安全漏洞(缓冲区溢出)。 使用std::size_t 而不是int 作为数组索引。

【讨论】:

    【解决方案2】:

    你使用'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;
    }
    

    【讨论】:

    【解决方案3】:

    正如@Erlkoenig 所说:

    "你需要使用 i:

    if(arr[i]==a) 完整的 else-case 是多余的;去掉它。此外,您必须确保 n std::size_t instead 或int 作为数组索引。"

    另外n++ 可能会给你一个分段错误(取决于没有开始的 n 以及你能多快找到“要查找的数字”。我很确定如果该数字不在数组中,你会得到分段错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-06
      • 2018-10-14
      • 2021-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多