C++ Stroustrup的代码审查-编程原理-Ch-4-问题:3-错误:向量下标超出范围
将双值序列读入向量。将每个值都视为 一条给定路线上两个城市之间的距离。计算和打印 总距离(所有距离之和)。找到并打印最小的 两个相邻城市之间的最大距离。查找并打印 两个相邻城市之间的平均距离 我遇到的问题是,我得到一个调试错误,指出我的向量下标超出范围。我似乎看不出这是在哪里发生的C++ Stroustrup的代码审查-编程原理-Ch-4-问题:3-错误:向量下标超出范围,c++,c++17,C++,C++17,将双值序列读入向量。将每个值都视为 一条给定路线上两个城市之间的距离。计算和打印 总距离(所有距离之和)。找到并打印最小的 两个相邻城市之间的最大距离。查找并打印 两个相邻城市之间的平均距离 我遇到的问题是,我得到一个调试错误,指出我的向量下标超出范围。我似乎看不出这是在哪里发生的 #include "pch.h" #include <iostream> #include <string> #include <vector> #include <algo
#include "pch.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using std::cout;
using std::cin;
using std::vector;
using std::string;
int main()
{
// Read a sequence of double values into a vector
vector <double> distance; // declaring the vector named "distance"
double sum = 0;
double smallest;
double greatest;
for (double x; cin >> x;) { // read into distance, to terminate putting values in vector use anything that is not of variable type of vector
distance.push_back(x); // put distance into vector
cout << '\n';
for (int i = 0; i < distance.size(); i = i + 1) { // keeping track of elements in vector by displaying them
cout << distance[i] << '\n';
}
}
for (int i = 0; i < distance.size(); i = i + 1) { // adding up all values of vector by iterating through all elements
sum = sum + distance[i];
}
cout << "The total sum of all the elements in the vecotr is: " << sum << '\n';
for (int i = 0; i < distance.size(); i = i + 1) { // determining the smallest value in the vector
if (smallest <= distance[i]) {
smallest = distance[i];
}
}
cout << "The smallest value in the vector is: " << smallest << '\n';
for (int i = 0; i < distance.size(); i = i + 1) { // determining the greatest value in the vector
if (greatest >= distance[i]) {
greatest = distance[i];
}
}
cout << "The smallest value in the vector is: " << smallest << '\n';
cout << "The mean distance between two neigbouring cities is: " << sum / distance.size() << '\n';
}
#包括“pch.h”
#包括
#包括
#包括
#包括
#包括
使用std::cout;
使用std::cin;
使用std::vector;
使用std::string;
int main()
{
//将双值序列读入向量
向量距离;//声明名为“距离”的向量
双和=0;
双最小;
双倍最大;
对于(double x;cin>>x;){//读入距离,要终止将值放入向量中,请使用任何非变量类型的向量
距离。推回(x);//将距离放入向量
coutBjarne希望您在标准库中找到适合特定问题的函数
例如
“元素的总和是…”
环顾四周,这里描述了您想要/需要的大多数函数调用
像这样运行你的程序
myprog < inputdoubles.txt
myprog
使用调试器逐步检查代码以查看错误发生的位置。我愿意打赌它位于第一个for
循环中(特别是在该循环中嵌套的for
区域周围)。可能是因为我尝试使用调试器并将断点设置为“for”我设置了一个循环来跟踪我的向量,我马上就遇到了一个错误。但问题是,当我写代码时,整个代码时钟都工作了。@dc3rd你传递的输入是什么?我传递的是double
到我的输入最小的是未初始化的。最大的也是未初始化的。我不认为这是他希望我们在书的早期就使用这种技术。到目前为止,标准库只是顺便讨论过,没有明确解释如何使用它们,以及如何通过它们的文档找到必要的函数调用。
myprog < inputdoubles.txt