无法停止读取 c++ 中的行
Can't stop reading lines in c++
以下代码适用于 10 月 17 日到期的家庭作业。问题指出"编写一个带有循环的程序,允许用户输入一系列数字。输入所有数字后,程序应显示输入的最大和最小数字。
#include "stdafx.h"
#include <algorithm>
#include <array>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
bool isNumeric(string aString)
{
double n;
istringstream is;
cin >> aString;
is.str(aString);
is >> n;
if (is.fail())
{
return false;
}
return true;
}
vector<double> limits(vector<double> a)
{
// Returns [min, max] of an array of numbers; has
// to be done using std::vectors since functions
// cannot return arrays.
vector<double> res;
double mn = a[0];
double mx = a[0];
for (unsigned int i = 0; i < a.size(); ++i)
{
if (mn > a[i])
{
mn = a[i];
}
if (mx < a[i])
{
mx = a[i];
}
}
res.push_back(mn);
res.push_back(mx);
return res;
}
int main()
{
string line = " ";
vector<string> lines;
vector<double> arr;
cout << "Enter your numbers: " << endl;
while (!line.empty() && isNumeric(line))
{
getline(cin >> ws, line);
if (line.empty() || !isNumeric(line))
{
break;
}
lines.push_back(line);
transform(line.begin(), line.end(), line.begin(), [](char32_t ch) {
return (ch == ' ' ? ' 00' : ch);
}); // Remove all spaces
arr.push_back(atof(line.c_str()));
}
vector<double> l = limits(arr);
cout << "nMinimum: " << l[0] << "nMaximum: " << l[1] << endl;
return 0;
}
上面的代码是我所拥有的。但是,它并不总是输出正确的最大值,并且仅输出"0"作为最小值。我似乎找不到这有什么问题,所以如果有人能帮忙,那就太好了。
至少,您的问题似乎在于在 limits()
函数中将 min 的值初始化为 0。因此,如果你有一个 [1, 2, 3, 4] 的数组,它将检查每个元素,并看到它们都不小于 0,将 0 作为最小值。若要解决此问题,可以将初始值 mn
设置为数组的第一个元素。请注意,您必须检查以确保数组至少有一个元素,以避免可能的溢出错误。
对于最大值,我不确定您有什么样的不一致,但是如果您的数组仅包含负值,则会遇到与最小值相同的问题,其中初始值高于任何实际值。
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 为什么在读取文件大小时文件IO速度会发生变化
- 正在读取二进制文件(is_open)
- 如何在c++中从文本文件中逐行读取整数
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- 独立读取-修改-写入顺序
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 一种在C++中读取TXT配置文件的简单方法