【发布时间】:2022-01-05 00:46:20
【问题描述】:
这是我的代码,我想尝试将我的数组与数字进行比较,但我给了我一些错误 基本上,我正在尝试通过线性搜索找到一个数字并在 C++ 中打印该数字的索引
// linear search
#include <iostream>
using namespace std;
int search(int arr, int n, int x)
{
int i=0;
for (i = 0; i < n; i++){
if (arr[i] == x){
return i;}
}
return -1;
}
// Driver code
int main(void)
{
int size;
int temp;
cout << "Enter Size of Arry";
cin >> size;
int arr[size];
for(int i=0;i<size;i++){
cout << "Enter a " << i << "Element of your arry : ";
cin >> temp;
arr[i]=temp;
}
cout << "Enter the number that you will find index";
int x;
cin >> x;
// Function call
int result = search(arr, size, x);
(result == -1)
? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
这是错误
PS C:\Users\talha\OneDrive\Desktop\Study_Material\DSA_lab\cs201149_lab1_3C> g++ Q1.cpp -o Q11.exe
Q1.cpp: In function 'int search(int, int, int)':
Q1.cpp:9:12: error: invalid types 'int[int]' for array subscript
if (arr[i] == x){
^
Q1.cpp: In function 'int main()':
Q1.cpp:35:34: error: invalid conversion from 'int*' to 'int' [-fpermissive]
int result = search(arr, size, x);
^
Q1.cpp:5:5: note: initializing argument 1 of 'int search(int, int, int)'
int search(int arr, int n, int x)
^~~~~~
PS C:\Users\talha\OneDrive\Desktop\Study_Material\DSA_lab\cs201149_lab1_3C>
【问题讨论】:
-
arr不是int search(int arr, int n, int x)中的数组,而是一个整数。
标签: c++ arrays compiler-errors function-declaration