zoukankan      html  css  js  c++  java
  • 读取文本文件里的数字求平均值

    #include<iostream>
    #include<fstream>
    #include<cstdlib>
    using namespace std;
    const int SIZE=60;
    int main()
    {
    char filename[SIZE];
    ifstream infile;
    cout<<"enter name of data file:"<<endl;
    cin.getline(filename,SIZE);
    infile.open(filename);
    if(!infile.is_open())
    {
    cout<<"could not open the file"<<filename<<endl;
    cout<<"program terminating. ";
    exit(EXIT_FAILURE);
    }
    double value;
    double sum=0.0;
    int count=0;
    infile>>value;
    while(infile.good())
    {

    cout<<value<<" "<<endl;
    ++count;
    sum+=value;
    infile>>value;

    }
    if (infile.eof())//看看循环结束的原因是不是因为遇到结束符了
    cout<<"end of file reached. ";
    else if(infile.fail())
    cout<<"input terminated by data mismatch. ";
    else cout<<"in put terminated for unkown reason. ";
    if(count==0)
    cout<<"no data processed. ";
    else
    {
    cout<<"items read:"<<count<<endl;
    cout<<"sum:"<<sum<<endl;
    cout<<"average:"<<sum/count<<endl;

    }
    infile.close();

    return 0;

    }

    结果图片:

  • 相关阅读:
    Cinema in Akiba(线段树)
    SGU
    632-掷骰子
    ZOJ
    nyoj 1129 Salvation(搜索)
    symbol table meaning
    C/C++编译和链接过程详解 (重定向表,导出符号表,未解决符号表)
    编译链接 C++
    while(cin.eof)出错 poj
    华为oj 购物单
  • 原文地址:https://www.cnblogs.com/sweeeper/p/4642506.html
Copyright © 2011-2022 走看看