C++读取文本文件
时间: 1ms 内存:128M
描述:
在文件f1.dat中,提供了N(N是一个很大的数,程序中不需要用到)个正整数。请编程序,输出文件中前n(n<N)个数中的最大值。
f1.dat中的前10个数据如下,请在调试程序时,自建f1.dat文件,其内容是10个整数。
52
69
21
29
65
79
72
27
35
24
输入:
整数n,代表输出的最大值是f1.dat文件中前n个数中的最大值
输出:
f1.dat文件中前n个数中的最大值。由于f1.dat已经在题目中给定,这个最大值取决于文件内容。就题目描述部分给出的数据:输入n为5时,输出“max number: 69”;输入n为8时,输出“max number: 79”。
示例输入:
5
示例输出:
max number: 69
提示:
参考答案(内存最优[1268]):
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int max;
int num[10];
ofstream ofile;
ofile.open( "f2.dat",ios::out);
ifstream ifile;
ofile<<52<<endl;
ofile<<69<<endl;
ofile<<21<<endl;
ofile<<29<<endl;
ofile<<65<<endl;
ofile<<79<<endl;
ofile<<72<<endl;
ofile<<27<<endl;
ofile<<95<<endl;
ofile<<24<<endl;
ofile.close();
ifile.open("f2.dat",ios::in&ios::app);
for(int i=0;i<10;i++)
ifile>>num[i];
int n;
cin>>n;
if(n<=10)
{max=num[0];
for(int j=1;j<n;j++)
{
if(num[j]>max)max=num[j];
}
cout<<"max number: "<<max<<endl;
}
else
{for(int j=1;j<10;j++)
{
if(num[j]>max)max=num[j];
}cout<<"max number: "<<max<<endl;
}
return 0;
}
参考答案(时间最优[0]):
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int max;
int num[10];
ofstream ofile;
ofile.open( "f2.dat",ios::out);
ifstream ifile;
ofile<<52<<endl;
ofile<<69<<endl;
ofile<<21<<endl;
ofile<<29<<endl;
ofile<<65<<endl;
ofile<<79<<endl;
ofile<<72<<endl;
ofile<<27<<endl;
ofile<<95<<endl;
ofile<<24<<endl;
ofile.close();
ifile.open("f2.dat",ios::in&ios::app);
for(int i=0;i<10;i++)
ifile>>num[i];
int n;
cin>>n;
if(n<=10)
{max=num[0];
for(int j=1;j<n;j++)
{
if(num[j]>max)max=num[j];
}
cout<<"max number: "<<max<<endl;
}
else
{for(int j=1;j<10;j++)
{
if(num[j]>max)max=num[j];
}cout<<"max number: "<<max<<endl;
}
return 0;
}
题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。
