文件读写之从A.txt(内容:多行数字)中计算数字总和以及平均数

C++文件读取和写入操作的方法:

1、使用“<<” 和“>>” 操作符;

2、使用“istream::read” 和"ostream::write"方法;

3、使用“istream::get”和“ostream::put”方法;

今天我用的是"<<"和“>>”方式:

一、相关代码

#include
#include
#include
int main(int argc, char *argv[])
{
    std::ifstream ifs("A.txt", std::ios::in);
    if(!ifs.is_open())
    {
        std::cerr << "open file failed..." << std::endl;
        return 0;
    }
    double sum = 0;
    int count = 0;
    while(!ifs.eof())
    {
        double n = 0;
        ifs >> n;
        sum += n;
        count++;
        std::cout << std::setprecision(9) << n <

二、运行结果

其中A.txt中的数字是用 excel表格的RAND() *100生成的

文件读写之从A.txt(内容:多行数字)中计算数字总和以及平均数_第1张图片文件读写之从A.txt(内容:多行数字)中计算数字总和以及平均数_第2张图片

 

 

你可能感兴趣的:(C/C++,c++)