Max和Min是真的,而不是数字,我该怎么办



我需要数组中的最小值和最大值,但它告诉我函数的地址总是为true,而不是数字。我不知道该改变什么。

#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;
}

这里没有打印最大值,而是打印一个隐式转换为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::beginstd::end将迭代器返回到数组的开头和结尾。这适用于std::array和C样式数组。

还要注意,std::accumulate可以用于轻松地计算总和。你不需要自己写一个循环。


另请参阅Iterator=pointer?或者它是什么?有关迭代器和指针以及区别的更多信息。

相关内容

最新更新