2013-07-19 206 views
0

所以這個程序會計算和打印用戶輸入序列的最大值,最小值,平均值和總和。我發現的唯一問題是,當輸入一個符號時,它輸出的結果是錯誤的,但仍然「添加」它是ascii代碼的總和,搞亂了結果。另外,如果其他人的數字和字母如1361351P,它仍然讀取它。任何幫助表示讚賞。C++總和,平均值,最大值,最小值驗證問題

/** C2.cpp 
     * Test #2 Problem C2 
     * Robert Uhde 
     * This program calculates and prints the largest, smallest, average, 
     * and sum of a sequence of numbers the user enters. 
     */ 
#include <iostream> 
using namespace std; 

// Extreme constants to find min/max 
const double MAX = 1.7976931348623157e+308; 
const double MIN = 2.2250738585072014e-308; 


// Create generic variable T for prototype 
template <class T> 
// Prototype dataSet that with request inputs and calculate sum, average, largest and smallest numbers. 
T dataSet(T &sum, T &largest, T &smallest, T avg); 

int main(){ 
    // Intro to program 
    cout << "This program calculates and prints the largest, smallest," 
     << endl << "average, and sum of a sequence of numbers the user enters." << endl << endl; 
    // defined used variables in longest double format to include as many types as possible with largest range 
    double avg = 0, sum = 0, max, min; 
    // Call dataSet which returns avg and return references 
    avg = dataSet(sum, max, min, avg); 
    // Output four variables 
    cout << endl << "The largest of the sequence you entered is: " << max << endl; 
    cout << "The smallest of the sequence you entered is: " << min << endl; 
    cout << "The sum of the sequence you entered is: " << sum << endl; 
    cout << "The average of the sequence you entered is: " << avg << endl; 
    system("pause"); 
    return 0; 
} 

// Create generic variable T for dataSet 
template <class T> 
T dataSet(T &sum, T &max, T &min, T avg){ 
    T num; 
    min = MAX, max = MIN; 
    // count number of valid numbers 
    int count = 0; 
    // Repeat this loop until ^Z 
    do{ 
     cout << "Enter a sequence of numbers: (^Z to quit) "; 
     cin >> num; 
     // if valid, then increment count by 1, add to sum, find out if it's new max or min 
     if(cin.good() && (typeid(num) == typeid(int) || typeid(num) == typeid(double))){ 
      count++; 
      if(num > max) 
       max = num; 
      sum += num; 
      if(num < min) 
       min = num; 
     } 
     // if user enters ^Z break out 
     else if(cin.eof()) 
      break; 
     // If there is some sort of type error, print so and clear to request again 
     else{ 
      cout << "Error. Try Again.\n"; 
      cin.clear(); 
      cin.ignore(80, '\n'); 
     } 
    }while(true); 

    // Calculate average and then return 
    avg = sum/count; 
    return avg; 
} 

回答

0

你的空調檢查需要一些更多的工作。我會用更具體的條件checkings如因而isalpha或ISDIGIT哪些是因爲以下這些條件檢查的一部分不夠好

if(cin.good() && (typeid(num) == typeid(int) || typeid(num) == typeid(double))) 

好運!

相關問題