2017-10-15 30 views
0

以下代碼用於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」作爲最小值。我似乎無法找到這個問題,所以如果任何人都能幫上忙,那就太棒了。

+1

你正試圖一次做兩件新事物。分開處理*,並告訴我們您需要哪一個幫助。 – Beta

+0

現在只有一個問題。現在開心?! –

+0

如果您的輸入例行程序正在運行,並且您在計算最小/最大值時遇到問題,請使用硬編碼輸入編寫一個更簡單的測試程序,然後將其寫入您的問題中。如果你的問題是你的輸入例程不起作用,請描述它正在做什麼和錯在哪裏。 –

回答

0

至少,你的問題似乎是因爲你的limits()函數初始化min的值爲0.所以如果你有一個[1,2,3,4]的數組,它會檢查每個元素,並且看到它們中的任何一個都不小於0,則保留0作爲最小值。要解決這個問題,可以將初始值mn設置爲數組的第一個元素。請注意,您必須檢查以確保數組至少有一個元素以避免可能的溢出錯誤。

對於最大值,我不確定你有什麼樣的不一致性,但是如果你的數組只包含負值,那麼你會遇到與最小值相同的問題,其中初始值高於實際值。

+0

好的。第一部分。 –

+0

@ElEctric,你仍然得到最大的錯誤值?如果是這樣,你能舉個例子嗎? –