C++:创建文件进行存数,并且判断最大值

题目概述:
有一个整型数组,含10个元素,从键盘输入10整数,存放到磁盘,并且输出其中最大的数和其序号。
编程:
#include< iostream>
#include< fstream>
using namespace std;
int main()
{
int a[10];
ofstream outfile(“f1.dat”, ios::out );//定义输出文件流对象,打开磁盘“f1.dat”,out是往磁盘中写。
if (!outfile)//如果打开失败,outfile返回0值
{
cerr << “open error!” << endl;
exit(1);
}
for (int i = 0; i < 10; i++)
{
cin >> a[i];
outfile << a[i] << " ";//向磁盘“f1.dat”输出数据,也是文件向外展示数据。
}
outfile.close();//关闭磁盘文件
int max, order, b[10];
ifstream infile(“f1.dat”, ios::in | ios::_Nocreate);//定义输入文件流对象,in是读取文件数据
if (!infile)
{
cerr << “open error!” << endl;
exit(1);
}
for (int i = 0; i < 10; i++)
{
infile >> b[i];//将从文件中读的数据放入b[i]中
cout << b[i] << " ";
}
cout << endl;
max = b[0];
order = 0;
for (int i = 0; i < 10; i++)
{
if (max < b[i])
{
max = b[i];
order = i;
}
}
cout << "max= " << max << "order= " << order << endl;
infile.close();//关闭文件
return 0;
}
上机实践:
在这里插入图片描述

在这里插入图片描述

Guess you like

Origin blog.csdn.net/qq_50426849/article/details/121877404