2013-07-19 2 views
0

Итак, эта программа вычисляет и печатает самую большую, наименьшую, среднюю и сумму последовательности, которую вводит пользователь. Моя единственная проблема, которую я обнаружил, заключается в том, что когда вводится символ, он выводит ее неправильно, но все же «добавляет» это код ascii в сумму, испортил результаты. Кроме того, если кто-то еще число и буква, такие как 1361351P, он все еще читает. Любая помощь приветствуется.C++ Sum, Average, Largest, Smallest issue validation

/** 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

Ваш чек кондиционирование нуждается больше работы. Я хотел бы использовать более конкретные условие поверки, такие как IsAlpha или isdigit, которые являются частью, так как эти проверки состояния ниже не хватает

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

удачи!

хорошо