0

したがって、このプログラムは、ユーザーが入力したシーケンスの最大、最小、平均、および合計を計算して出力します。私が見つけた唯一の問題は、記号が入力されたときにそれが間違っていると出力されることですが、それでも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;
}
4

1 に答える 1

0

コンディショニング チェックにはもう少し作業が必要です。以下のこれらの条件チェックは十分ではないため、の一部である isalpha や isdigit などのより具体的な条件チェックを使用します

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

頑張ってください!

于 2013-07-19T15:20:42.673 に答える