我正在尝试显示向量的最大值和最小值(以及其他内容)。最大值显示正常,但最小值不断变为0.唯一一次不是0,它最终显示数据列表的最终值。
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
fstream file;
file.open("dataWin.txt");
vector<float> dist;
while(file.eof() == false)
{
string miles;
getline(file, miles);
float milesNum = atof(miles.c_str());
dist.push_back(milesNum);
}
float max = 0.0;
float min = 1.0;
float sum = 0.0;
float secHour = 3600;
float lastRecord = 238857;
for(int i = 0; i < dist.size(); i++)
{
if(dist[i] < min)
min = dist[i];
if(dist[i] > max)
max = dist[i];
sum += dist[i];
}
float avg = (float)sum / dist.size();
float lastSeconds = (float)lastRecord / (float)avg;
float deadline = (float)lastSeconds / (float)secHour;
cout << "National Aeronautics and Space Administration - NASA" << endl;
cout << "EYES ONLY" << endl << endl;
cout << "Statistics on solar object 326 Alba" << endl;
cout << "Danger level: HIGH" << endl << endl;
cout << "Maximum travel distance: " << max << " miles per second." << endl;
cout << "Minimum travel distance: " << min << " miles per second." << endl;
cout << "Average travel distance: " << avg << " miles per second." << endl << endl;
cout << "WARNING! OBJECT 326 Alba WILL IMPACT IN " << deadline << " HOURS!" << endl;
file.close();
return 0;
}
如何获取要显示的列表的实际最小值?
答案 0 :(得分:2)
问题是当输入结束时getline
调用将失败并且它不会更新字符串,那么您将空字符串转换为在atof
调用失败的浮点数(如果atof
失败,它将返回0.0
)并将该值推送到向量中。向量中的最小值现在为0
,算法正确地将其作为最小值。
如果要在C ++中编写代码,并假设输入的唯一内容是浮点数和空格,则可以通过直接读取浮点数来使代码更简单:
float miles;
while ( std::cin >> miles ) {
dist.push_back( miles );
}
更简单的是,您可以通过使用STL中的迭代器和算法来完全避免循环:
std::vector<float> dist;
std::copy( std::istream_iterator<float>( std::cin ), std::istream_iterator<float>(),
std::back_inserter( dist ) );
std::cout << "Max: " << *std::max_element( dist.begin(), dist.end() ) << "\n";
std::cout << "Min: " << *std::min_element( dist.begin(), dist.end() ) << "\n";
std::cout << "Sum: " << std::accumulate( dist.begin(), dist.end() ) << std::endl;
这只是为了展示现有算法可以做些什么。在您的特定情况下,我将使用std::copy
和std::istream_iterator
来读取输入,但是为了处理已读取的数字,我将展开手动循环(以便可以计算所有的min,max和sum)在一次通过中,上面的STL示例分三次进行。)
答案 1 :(得分:1)
此:
while(file.eof() == false)
{
string miles;
getline(file, miles);
应该是:
string miles;
while( getline(file, miles) )
{
你在哪里接受你需要从中调用eof()的想法?你不这样做,而且你这样做是错误的!