Re: [问题] C++ 读档(.dat)>跨行计算>输出

楼主: devcc (游侠)   2019-12-31 14:30:30
※ 引述《devcc (凯西)》之铭言:
: 问题(Question):
: 我想做一个简单的资料分析处理
: 已经先有dat档
: 因为数值变动很大,想做前两个或是前三个数值结果相加平均
: 同行的计算平均会,但跨行的不知道怎么去写计算
: 喂入的资料(Input):
: ex:
: .DAT
: 1 10
: 2 3
: 3 11
: 4 9
: 5 7
: 6 1
: 预期的正确结果(Expected Output):
: 以前两个做平均出来希望如下
: 1 6.5
: 2 7
: 3 10
: 4 8
: 5 4
经过半天研究 因为主要我不知道原本的数据量会有多少
这是我写的code 希望对别人有帮助
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main ()
{
///计算行数
ifstream fin;
int line = 0;
string tmps;
fin.open("C3_SM_1.dat",ios::in);//开档读取
while(getline (fin,tmps))
{
line++;//一行一行读,每读一行就加一
}
fin.close();//关闭文件
cout <<"此档共"<< line <<"行"<< endl;//输出行数
///写入阵列
int i,j,a,b;
b=3;
a=line;
double matrix[a][b];
ifstream input("C3_SM_1.dat",ios::in);
for(i=0;i<a;i++)
for(j=0;j<(b-1);j++)
input>>matrix[i][j];
input.close();
///开档+计算
ofstream fout("C3_SM_1_arr.dat");
if(!fout){ cout << "开档失败" << endl; } // 检查开档成功与否
for(i=0;i<(a-2);i++)
{
matrix[i][2]= (matrix[i][1]+matrix[(i+1)][1]+matrix[(i+2)][1])/3;
fout<<matrix[i][0]<<" "<<matrix[i][2]<<endl;
}
///输出显示
for(i=0;i<(a-2);i++)
for(j=0;j<b;j++)
cout<< matrix[i][j]<<" "<<endl;
fout.close(); // 关闭档案
return 0;
}

Links booklink

Contact Us: admin [ a t ] ucptt.com