我在这个程序中返回多个值时遇到了一些问题,这些值计算了min,max,mean,median.我做的第一件事是传递引用参数,它起作用 - 但我读到创建结构或类是返回多个值的首选方法.
所以我尝试了,但是我没能取得好成绩.这是我到目前为止所得到的.
#include "std_lib_facilities.h"
struct maxv{
int min_value;
int max_value;
double mean;
int median;
};
maxv calculate(vector<int>& max)
{
sort(max.begin(), max.end());
min_value = max[0];
int m = 0;
m = (max.size()-1);
max_value = max[m];
for(int i = 0; i < max.size(); ++i) mean += max[i];
mean = (mean/(max.size()));
int med = 0;
if((max.size())%2 == 0) median = 0;
else
{
med = (max.size())/2;
median = max[med];
}
}
int main()
{
vector<int>numbers;
cout << "Input numbers. Press enter, 0, enter to finish.\n";
int number;
while(number != 0){
cin >> number;
numbers.push_back(number);}
vector<int>::iterator i = (numbers.end()-1);
numbers.erase(i);
maxv result = calculate(numbers);
cout << "MIN: " << result.min_value << endl;
cout << "MAX: " << result.max_value << endl;
cout << "MEAN: " << result.mean << endl;
cout << "MEDIAN: " << result.median << endl;
keep_window_open();
}
Run Code Online (Sandbox Code Playgroud)
显然,计算函数中的变量是未声明的.我只是不确定如何以正确的方式实现它以返回正确的值.到目前为止,我已经尝试过的东西,我已经得到了很好的解释.任何帮助将不胜感激 - 谢谢.
PS我已经查看了关于这个主题的其他线程,我仍然有点困惑,因为需要传递给calculate()的参数和maxv结构中的变量之间没有任何差异.
有三种方法可以做到这一点.
1)从calculate函数返回一个maxv实例
maxv calculate(vector<int>& max)
{
maxv rc; //return code
... some calculations ...
... initialize the instance which we are about to return ...
rc.min_value = something;
rc.max_value = something else;
... return it ...
return rc;
}
Run Code Online (Sandbox Code Playgroud)
2)通过引用传入maxv实例
void calculate(vector<int>& max, maxv& rc)
{
... some calculations ...
... initialize the instance which we were passed as a parameter ...
rc.min_value = something;
rc.max_value = something else;
}
Run Code Online (Sandbox Code Playgroud)
3)假设calculate是maxv结构的一种方法(甚至更好,构造函数)
struct maxv
{
int min_value;
int max_value;
double mean;
int median;
//constructor
maxv(vector<int>& max)
{
... some calculations ...
... initialize self (this instance) ...
this->min_value = something;
this->max_value = something else;
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
461 次 |
| 最近记录: |