。构建编译器后,出现了“ int之前预期的初始化”错误,并试图学习c ++,但我一直陷入困境

emphasized text

#include <iostream>

using namespace std;
int lsearch(int[],int,int);

int main()

 {


int N,ITEM,INDEX,ar[20];

cout<<"how many elements?(max 20)\n"<< endl;

cin>>N ;

cout<<"\n enter elements\n";

for(int i=0;i<N;i++)

cin>>ar[i];

cout<<"your array is as follows :\n";

for (int i =0;i<N ;i++ )


cout<<ar[i] <<"\n";

cout<<"enter element to be searched for:\n";

cin>>ITEM;

INDEX=lsearch(ar[ ],N,ITEM);

if(INDEX==-1)

cout<<"element not found";

else

cout<< "item found at index:"<<INDEX<<"position:"<<INDEX+1;

return 0;
}

int lsearch (int ar[ ],int N,int ITEM)
{

    for (int i=0;i<N ;i++ )
{
    if  ( ar [i]==ITEM)

    return i;
}

        return -1;
}

'''''''''''''''''''''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''

提前致谢 :)

评论
  • 疯癫范er
    疯癫范er 回复

    You forgot a ; in line 4 of your code dude! (In the image you posted.)

    Actually there is no need of line 4: int lsearch(int [], int, int). Because in the next line you are defining the function itself. You can skip the prototype declaration if you wish.

    从下一次起,请发布正确的代码,而不仅仅是图像。所谓代码,是指导致错误的实际代码。图片中的代码与您在帖子中键入的代码不同!

    In your typed code you are calling lsearch as lsearch(arr[], N, ITEM) [line 34]. A call should be made like this: lsearch(arr, N, ITEM).

    这是您更正的代码:

    #include <iostream>
    using namespace std;
    
    int lsearch(int [], int, int);
    
    int main() {
        int N, ITEM, INDEX, ar[20];
        cout << "How many elements? (max 20): " << endl;
        cin >> N;
        cout << "Enter elements: " << endl;
        for (int i = 0; i < N; i++)
            cin >> ar[i];
        cout << "Your array is as follows: " << endl;
        for (int i = 0; i < N; i++)
            cout << ar[i] << endl;
        cout << "Enter the element to be searched for: " << endl;
        cin >> ITEM;
        INDEX = lsearch(ar, N, ITEM);
        if (INDEX == -1)
            cout << "Element not found!" << endl;
        else
            cout << "Item found at index: " << INDEX << " position: " << INDEX + 1 << endl;
        return 0;
    }
    
    int lsearch(int ar[], int N, int ITEM) {
        for (int i = 0; i < N; i++)
            if (ar[i] == ITEM)
                return i;
        return -1;
    }
    

    样品运行:

    How many elements? (max 20): 5
    Enter elements: 1 2 3 4 5
    Your array is as follows: 
    1
    2
    3
    4
    5
    Enter the element to be searched for: 4
    Item found at index: 3 position: 4
    

    这段代码实际上是相同的(我从您的图片中猜到了这段代码):

    #include <iostream>
    using namespace std;
    
    int lsearch(int ar[], int N, int ITEM) {
        for (int i = 0; i < N; i++)
            if (ar[i] == ITEM)
                return i;
        return -1;
    }
    
    int main() {
        // same as in above code
    }
    

    You should also check out this thread on why "using namespace std" is considered a bad practice.