【问题标题】:Find the smallest value in a vector查找向量中的最小值
【发布时间】:2016-03-16 17:03:55
【问题描述】:

在使用 STL 编程方面,我还是个新手,我想我已经掌握了窍门。但我对此有点困惑。我的目标是获取 5 个值,然后打印出我的值,打印其中的最大值,打印平均值,然后打印其中的最小值(我的问题)。似乎我的变量“low”被赋予了 0 的值,我不知道这是为什么。我已经测试过我的价值观是否被读入,据我所知,确实如此。因此,如果有人能告诉我为什么我似乎无法获得适当的最低值,我将不胜感激。感谢您的宝贵时间。

vector<double> vecList;
int x = 0;
double high = 0;
double low = 0;
double sum = 0;

cout << "Enter Integer Values, then press Ctrl(z) to Quit:" << endl;

for (int i=0; i < 5; i++)
{
 cin >> x;
 sum = sum + x;
 vecList.push_back(x);
}
vector<double>::iterator intVecIter;

cout <<"List contains: ";
for (intVecIter = vecList.begin(); intVecIter != vecList.end(); ++intVecIter)
cout << *intVecIter << " ";
for (int i=0; i < 5; i++)
 {
    if(vecList[i] > high)
    {
            high = vecList[i];
    }
// prints out "0"
    if(low > vecList[i])
    {
            low = vecList[i];
    }
 }
cout << endl << "Largest: "<< fixed << setprecision(2) << high << endl;
cout << "Smallest: "<< fixed << setprecision(2) << low << endl;
cout << "Average: " << fixed << setprecision(2)<< (sum/5);
return 0;

【问题讨论】:

标签: c++ arrays vector stl


【解决方案1】:

由于您正在尝试学习 STL,请查看 algorithms library,它有一些辅助函数,可以为给定范围提供最小值、最大值和总和(accumulate 是实际函数名称)。

【讨论】:

【解决方案2】:

你需要将low初始化为一个很大的值而不是0,否则这个

   if(low > vecList[i])

从来都不是真的

【讨论】:

  • 我觉得自己像个傻瓜!谢谢你。我完全忽略了这一点。
  • 或者只用low = vecList.front()初始化。
  • 如果您允许负数,您应该将 low 和 hight 都初始化为 vecList.front(),否则您总是会想出不会给出正确结果的输入。
猜你喜欢
  • 2015-10-11
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
  • 2017-07-20
  • 1970-01-01
  • 2019-06-01
  • 1970-01-01
  • 2019-01-18
相关资源
最近更新 更多