I need the minimum and maximum number out of an array but it is telling me that the address of function will always come out to true instead of a number. I can't figure out what to change.
#include <iostream>
using namespace std;
int main()
{
double num1[10] {0.61, 1.70, 0.52, 1.34, 0.25, 1.20, 0.46, 1.10, 1.68, 1.37}; //material used in february
double total1 {0};
float average1 {0};
int i;
for (i=0; i<10; i++)
{
total1 = total1 + num1[i];
}
average1 = total1/10.0; //average of material used in feb
double max1(double num1); // maximum of material used in feb
double min1(double num1); // minimum of material used in feb
cout << "Maximum is " << max1 << endl;
cout << "Average is " << average1 << endl;
cout << "Minimum is " << min1 << endl;
double num2[10] {1.64, 1.15, 1.34, 1.63, 0.93, 0.51, 1.13, 1.16, 1.56, 1.38}; //material used in march
double total2 {0};
float average2 {0};
int l;
for (l=0; l<10; l++)
{
total2 = total2 + num2[l];
}
average2 = total2/10.0; //average of material used in march
double max2(double num1); // maximum of material used in march
double min2(double num1); // minimum of material used in march
cout << "Maximum is " << max2 << endl;
cout << "Average is " << average2 << endl;
cout << "Minimum is " << min2 << endl;
return 0;
}
You are not printing a maximum here, you are printing a function pointer which is implicitly converted to bool
. It is never nullptr
, so it is true
.
// These two lines are actually forward-declarations of two functions
// called max1 and min1.
double max1(double num1);
double min1(double num1);
cout << "Maximum is " << max1 << endl; // printing function pointer here
cout << "Average is " << average1 << endl;
cout << "Minimum is " << min1 << endl; // printing function pointer here
What you need instead is this:
#include <algorithm>
#include <numeric>
#include <array>
int main()
{
constexpr std::array<double, 10> num1 {
0.61, 1.70, 0.52, 1.34, 0.25, 1.20, 0.46, 1.10, 1.68, 1.37
};
double *max1 = std::max_element(std::begin(num1), std::end(num1));
double *min1 = std::min_element(std::begin(num1), std::end(num1));
double avg1 = std::accumulate(std::begin(num1), std::end(num1), 0.0)
/ num1.size();
// Note that we only need std::endl if we want to flush std::cout.
// Otherwise '\n' is enough.
std::cout << "Maximum is " << *max1 << '\n';
std::cout << "Minimum is " << *min1 << '\n';
std::cout << "Average is " << avg1 << '\n';
// ...
}
std::min_element
returns a pointer to the minimum in a range (in your case an array).
std::begin
and std::end
return iterators to the beginning and end of your array. This works with both std::array
and C-style arrays.
Also note that std::accumulate
can be used to compute the sum with ease. You don't need to write a loop for that yourself.
Also see Iterator = pointer? Or what is it? for more information on iterators and pointers and what the difference is.