不知道哪里有问题,输出一直不对😭😭
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
void main()
{
ofstream outfile("binary.dat", ios::binary);
if (!outfile.is_open())
{
cout << "打开失败" << endl;
exit(0);
}
double c[10], a[10], sum = 0, ave;
cout << "输入十个数"<<endl;
for (int i = 0; i <= 9; i++)
{
cin >> c[i];
outfile << c[i];
}
outfile.close();
ifstream infile("binary.dat", ios::binary);
if (!infile)
{
cout << "打开错误";
exit(1);
}
for (int i = 0; i <= 9; i++)
{
infile >> a[i];
sum += a[i];
}
ave = sum / 10;
cout << "总和为:" << sum << " " << "平均值为:" << ave << endl;
}
怎么个不对法???
用代码段贴一下代码
(1)if(!outfile)改成 if(!outfile.is_open())
(2)二进制读写文件需要用write和read函数。代码修改如下:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outfile("binary.dat",ios::out | ios::binary);
if(!outfile.is_open())
{
cout <<"打开失败"<<endl;
exit(0);
}
double c[10],a[10],sum = 0,ave;
cout <<"输入十个数:"<<endl;
for(int i=0;i<=9;i++)
{
cin >> c[i];
outfile.write((char*)&c[i],sizeof(double));
}
outfile.close();
ifstream infile("binary.dat",ios::in | ios::binary);
if(!infile.is_open())
{
cout <<"打开错误"<<endl;
exit(1);
}
for (int i = 0;i<=9;i++)
{
infile.read((char*)&a[i],sizeof(double));
sum += a[i];
}
infile.close();
ave = sum/10;
cout <<"总和为:"<<sum <<" "<<"平均值为:"<<ave<<endl;
return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!