我裂开

实践出真知啊

#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>// offer the exit()
double average(double sum, int num_of_items);
int main(void) {
    using namespace std;
    
    const int NAME_SIZE = 60;
    char fileName[NAME_SIZE];
    //string fileName;
    cout << "Please type a file name(.txt):\n";
    cin >> fileName;
    //fileName += ".txt";
    //const char* tempFileName = fileName.c_str();//a convention confusion for me :(
    ifstream inFile;
    inFile.open(fileName);//read from a file named fileName.txt
    
    //while the file could not be open
    if(!inFile.good()){
        cout << "There is an error\n";
        exit(EXIT_FAILURE);
    }

    const int SIZE = 10;
    double donation;
    double sum;
    //double list[SIZE];//we declare an array with 10 members
    int i = 0;
    for( (inFile >> donation).good() == 1 ;(inFile >> donation).good() == 1&&i<SIZE;i++){
    //Why this way -->    for( ( (cin >> donation).good() == 1 )&&(int i=0);;i++)    --> is wrong
        //list[i] = donation;//we get an array whose members are all type double
        sum += donation;
    }
    /*
    //we'll get the sum of all the items in double array list;
    double sum = 0;
    for(int j = 0;;i++){
        sum += list[i];
    }
    */
    double ave = average(sum, SIZE);
    cout << ave;
    
    inFile.close();
    
    return 0;
}


double average(double sum, int num_of_items){
    return sum/num_of_items;
}

 

posted @ 2020-12-01 00:32  VVEN2014  阅读(35)  评论(1)    收藏  举报