第七章习题参考答案
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
2
#include
#include
using namespace std;
void main()
{ double data[5]={3.333,4.555,21.56789,6.0034,7.9045};
for(int i=0;i<5;i++)
{
cout< } } 3 #include #include using namespace std; void main() { char c='B'; for(int i=1;i<9;i++) { cout< for(int j=1;j<=2*i-1;j++) cout< cout< } } 4 (1) #include #include using namespace std; void main() { int x,y; ofstream f1,f2; f1.open("f1.dat"); cout<<"请输入20个整数"< for(int i=1;i<=10;i++) { cin>>x; f1< } f2.open("f2.dat"); for(i=1;i<=10;i++) { cin>>y; f2< } f1.close(); f2.close(); } (2) #include #include using namespace std; void main() { int x,y; ifstream f1; ofstream f2; f1.open("f1.dat"); if(!f1) { cerr<<"f1.dat不存在!"< } f2.open("f2.dat",ios::app);//追加方式必须先声明ofstream对象,而不是fstream对象if(!f2) { cerr<<"f2.dat不存在!"< } for(int i=1;i<=10;i++) { f1>>x; f2< } f1.close(); f2.close(); } (3) #include #include using namespace std; void main() { fstream f2; f2.open("f2.dat",ios::in); if(!f2) { cerr<<"f2.dat不存在!"< } //读出数据保存在数组x中 int x[20]; for(int i=0;i<20;i++) { f2>>x[i]; } //排序 int t; for(i=0;i<20;i++) { for(int j=0;j<=19-i;j++) { if(x[j]>x[j+1]) { t=x[j]; x[j]=x[j+1]; x[j+1]=t; } } } //写回f2.dat ofstream f;//需要改变文件流对象为输出,从而可以写数据 f.open("f2.dat"); for(i=0;i<20;i++) f< f.close(); f2.close(); } 5 (1) #include #include #include using namespace std; class Employee { private: int id; string name; int age; int salary; public: Employee(int i,string xm,int a,int s):id(i),name(xm),age(a),salary(s){} int getid(){return id;} string getname(){return name;} int getsalary(){return salary;} int getage(){return age;} }; void main() { Employee e1(1,"zhansan",34,2000),e2(2,"lisi",31,2300);//简单起见,只生成了2个对象,同学们可以生成对象数组,提高效率 ofstream f; f.open("employee.txt"); f< f< f.close(); } (2) #include #include #include #include using namespace std; void main() { Employee e1(3,"woshi",31,5000),e2(4,"chufang",31,8300); ofstream f; f.open("employee.txt",ios::app); f< f< f.close(); } (3)