次のコードは、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」しか出力しません。私はこのことが間違っているのを見いだすことができないので、誰かがそれを助けることができれば偉大になるでしょう。
あなたはすぐに2つの新しいことをしようとしています。それらに取り組んでください*と、あなたが助けを必要とするものを教えてください。 – Beta
問題は1つだけです。今幸せです?! –
入力ルーチンが動作していて、min/maxの計算に問題がある場合は、より簡単なテストプログラムをハードコードされた入力で作成し、質問に入れてください。あなたの問題が入力ルーチンがうまくいかない場合、それが何をしているのか、何が間違っているのかを記述します。 –