问题描述
我需要数组中的最小和最大数字,但它告诉我函数的地址将始终为真,而不是数字。我不知道该更改什么。
#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.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;
}
解决方法
这里您没有打印最大值,而是要打印一个函数指针,该指针将隐式转换为bool
。永远不会nullptr
,所以永远是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
您需要的是:
#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
返回一个指向范围内最小值的指针(在您的情况下为数组)。
std::begin
和std::end
将迭代器返回到数组的开头和结尾。这适用于std::array
和C样式的数组。
还要注意,std::accumulate
可用于轻松计算总和。您无需自己为此编写循环。
有关迭代器和指针以及它们之间的区别的更多信息,请参见Iterator = pointer? Or what is it?。