以下代碼用於10月17日到期的作業分配。問題是「用一個循環編寫程序,讓用戶輸入一系列數字,輸入完所有數字後,程序應顯示輸入的最大和最小數字。」無法停止讀取C++行中的行
#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 == ' ' ? '\000' : 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」作爲最小值。我似乎無法找到這個問題,所以如果任何人都能幫上忙,那就太棒了。
你正試圖一次做兩件新事物。分開處理*,並告訴我們您需要哪一個幫助。 – Beta
現在只有一個問題。現在開心?! –
如果您的輸入例行程序正在運行,並且您在計算最小/最大值時遇到問題,請使用硬編碼輸入編寫一個更簡單的測試程序,然後將其寫入您的問題中。如果你的問題是你的輸入例程不起作用,請描述它正在做什麼和錯在哪裏。 –