c ++总和,平均,最大,最小的验证问题

时间:2013-07-19 15:14:18

标签: visual-c++

因此,该程序计算并打印用户输入的序列的最大,最小,平均和总和。我发现的唯一问题是,当输入一个符号时,它输出它是错误的,但仍然“”添加“它的ascii代码到总和,弄乱了结果。另外,如果其他人的数字和字母,如1361351P,它仍然可以读取它。感谢任何帮助。

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

1 个答案:

答案 0 :(得分:0)

您的调理检查需要更多工作。我会使用更具体的条件检查,如isalpha或isdigit,因为下面的这些条件检查不够好

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

祝你好运!