【发布时间】:2018-10-11 14:39:17
【问题描述】:
我正在尝试返回最大值。在 C++ 中的向量中的值,但我一直只得到最后一个值作为响应(我猜这是因为 if-else 循环在某种程度上没有进行比较,只是将下一个值分配给“maxVal”)。例如,下面的代码返回 30 作为答案。我究竟做错了什么?你能帮忙吗?
下面是代码->
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
double max (const vector<double>& myVector) {
int n = myVector.size();
double maxVal;
for (int i=0; i<=n-1; i++) {
if (maxVal <= myVector[i+1]) {
maxVal = myVector[i+1];
}
else {
maxVal = myVector[i];
}
}
return maxVal;
}
int main() {
vector<double> testVector;
testVector.push_back(10.0);
testVector.push_back(200.0);
testVector.push_back(30.0);
cout << max(testVector);
return 0;
}
【问题讨论】:
-
通常
i <= n-1会写成i < n。如果n是像std::size_t这样的无符号整数,这实际上很重要。 -
在每次迭代中,您都将
maxVal的值设置为当前元素或下一个元素。因此,您正在计算 最后两个向量元素的最大值。 -
请注意,
i+1在最后一次迭代中将超出向量的范围。 -
maxVal 未在函数 max () 中初始化。使用 double maxVal = myVector[0];
-
对不起,这是处理这种情况的错误方法:我建议您放置调试行(
cout或其他),并显示您的值 MaxVal 的进度,我, MyVector[i+1], ...,看看它们是如何演变的。像这样,您将了解问题所在以及如何处理。
标签: c++ loops for-loop if-statement