文件操作
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
struct student
{
char name[10];
int num;
float score[3];
float avr;
}stud[5];
void main()
{
float sum;
int i,j;
cout << "input the information of five student!"<<endl;
for(i = 0;i < 5;i++)
{
cout << "name:";
cin >> stud[i].name;
cout << "num:";
cin >> stud[i].num;
for(j = 0;j < 3;j++)
{
cout << "score" << j+1 << ":";
cin >> stud[i].score[j];
sum += stud[i].score[j];
}
stud[i].avr = sum /3;
cout << endl;
}
ofstream outfile("stud.dat");
if(!outfile)
{
cout << "open error!" << endl;
abort();
}
outfile<<"name num socre1 score2 score3 average"<<endl;
for(i = 0;i < 5;i++)
{
outfile << stud[i].name << " " << stud[i].num << " ";
for(j = 0 ;j < 3;j++)
{
outfile << stud[i].score[j] << " ";
}
outfile << stud[i].avr << endl;
}
outfile.close();
}
有五个学生,每个学生有3门课的成绩,从键盘输入以上数据(包括学生号,姓名,三门课成绩),
计算出平均成绩,况原有的数据和计算出的平均分数存放在磁盘文件"stud"中。*/
以上代码有啥错啊??求助。。。。。。。。。
[解决办法]
- C/C++ code
#include<iostream>#include<fstream>#include<iomanip>using namespace std;struct student{ char name[10]; int num; float score[3]; float avr;}stud[5];void main(){ float sum; int i,j; cout << "input the information of five student!"<<endl; for(i = 0;i < 5;i++) { cout << "name:"; cin >> stud[i].name; cout << "num:"; cin >> stud[i].num; for(j = 0;j < 3;j++) { cout << "score" << j+1 << ":"; cin >> stud[i].score[j]; sum += stud[i].score[j]; } stud[i].avr = sum /3; cout << endl; } ofstream outfile("stud.dat"); if(!outfile) { cout << "open error!" << endl; abort(); } outfile<<"name num socre1 score2 score3 average"<<endl; for(i = 0;i < 5;i++) { outfile << stud[i].name << " " << stud[i].num << " "; for(j = 0 ;j < 3;j++) { outfile << stud[i].score[j] << " "; } outfile << stud[i].avr << endl; } outfile.close(); }
[解决办法]
- C/C++ code
第一点:sum没有初始化。就加能算对嘛!sum = 0;这是问题根源,不是ofstream的问题第二点:/除法。最好把3写成3.0第三点:用double安全些