I was trying to define a function that will calculate the range of numbers in an array. and I got
"27:28: error: invalid operands of types '<unresolved overloaded function type>' and '<unresolved overloaded function type>' to binary 'operator-'"
#include <iostream>
#include <cmath>
usingnamespace std;
int range( int array[], int NumEl)
{
for (int p=0; p<NumEl; p++)
{
int max=array[0];
if (array[p] > max)
{
max=array[p];
}
}
for (int q=0; q<NumEl; q++)
{
int min=array[0];
if (array[q] < min)
{
min=array[q];
}
}
int difference = max - min;
return difference;
}
You have a scoping issue. Both 'std::min' and 'std::max' are built in function templates, the 'min' and 'max' that you are trying to refer to are outside of the scope for your math operation. The inclusion of the entire std namespace is part of the reason for the error being presented the way it is, if you were to only include the parts that you are aware of then you would have gotten a straight forward 'undeclared variable' error.
#include <iostream>
#include <cmath>
int difference(int array[], int NumEl)
{
int max, min;
max=min=array[0];
for (int i=0; i<NumEl; i++)
{
if (array[i]>max)
max=array[i];
if (array[i]<min)
min=array[i];
}
return max-min;
}
int difference(int array[], int NumEl);
usingnamespace std;
int main()
{
int range;
int elements;
int ar[]={};
cout << "How many elements are in the array?"<<endl;
cin >> elements;
cout << " enter the array: ";
cin >> ar[elements];
range = difference (ar, elements);
cout << "The range of this array is "<< range <<endl;
return 0;
}
It will run now but it wouldn't give me the answer I want.
int ar[]={}; //Illegal C++ - zero sized array. You should write size or initializers explicitely
cout << "How many elements are in the array?"<<endl;
cin >> elements; //Read amount of elements
cout << " enter the array: ";
cin >> ar[elements]; //Write into element past the last one: would be useless in any case
#include <iostream>
#include <cmath>
int difference(int array[], int NumEl)
{
int max, min;
max=min=array[0];
for (int i=0; i<NumEl; i++)
{
if (array[i]>max)
max=array[i];
if (array[i]<min)
min=array[i];
}
return max-min;
}
int difference(int array[], int NumEl);
usingnamespace std;
int main()
{
int range;
int elements = 3;
int ar[elements];
cout << "How many elements are in the array?"<<endl;
cin >> elements;
cout << " enter the array: ";
for (int count=0; count<elements; count++)
cin >> ar[count];
range = difference (ar, elements);
cout << "The range of this array is "<< range <<endl;
return 0;
}