#include <fstream>
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int i;
int numbers, count;
time_t t;
double d; // считываемое число
double sum; // сумма
double avg; // среднее
long begin, end;
int size;
srand(time(&t)); // инициализируем генератор случайных чисел
// создаем файл
ofstream fdata("data.dat", ios::binary|ios::out|ios::trunc);
if (!fdata)
{
cerr << "Unable to write to data.dat" << endl;
system("Pause");
exit(1);
}
// записали случайное количество случайных чисел
// в файл "data.dat"
numbers = (25+rand()%100)/5;
for (int i = 0; i < numbers; i++)
{
d = rand()%100-50+static_cast<double>(rand())/100;
fdata.write((char *)&d, sizeof(double));
}
fdata.close();
fstream bin_data("data.dat", ios::binary|ios::in|ios::out);
if (!bin_data)
{
cerr << "Unable to write to data.dat" << endl;
system("Pause");
exit(1);
}
// Вычисляем размер файла
bin_data.seekg(0, ios::end);
end=bin_data.tellg();
bin_data.seekg(0, ios::beg);
begin=bin_data.tellg();
size = (end-begin)/sizeof(double);
// Содержимое файла до изменения
bin_data.seekg(0);
cout << "Before ";
for (int i=0; i<size; i++)
{
bin_data.read((char *)&d, sizeof(double));
cout << d << ' ';
}
cout << endl;
// Вычисление суммы и среднего
sum = 0;
bin_data.seekg(0);
for (int i=0; i<size; i++)
{
bin_data.read((char *)&d, sizeof(double));
sum+=d;
}
avg = sum / size;
cout << endl;
cout << "sum = " << sum << endl;
cout << "numbers= " << numbers << endl;
cout << "avg = " << avg << endl;
// Внесение изменений
bin_data.seekg(0);
for (int i=0; i<size; i++)
{
long curr=bin_data.tellp();
bin_data.read((char *)&d, sizeof(double));
if (d<avg)
{
d*=2;
bin_data.seekp(curr, ios::beg);
bin_data.write((char *)&d, sizeof(double));
}
}
// Содержимое файла после изменений
bin_data.seekg(0);
cout << endl << "After ";
for (int i=0; i<size; i++)
{
bin_data.read((char *)&d, sizeof(double));
cout << d << ' ';
}
cout << endl;
bin_data.close();
system("pause");
return 0;
}
Before 327.84 314.4 106.42 257.3 6.97 255.51 -5.39 320.55 103.89 122.96 283.81 139.22 38.58 2.61 237.54 61.85 330.36 147.77 34.96
sum = 3087.15
numbers= 19
avg = 162.482
After 327.84 314.4 212.84 257.3 13.94 255.51 -10.78 320.55 207.78 245.92 283.81 278.44 77.16 5.22 237.54 123.7 330.36 295.54 69.92
Для продолжения нажмите любую клавишу . . .
Если Вы уже зарегистрированы на Портале - войдите в систему, если Вы еще не регистрировались - пройдите простую процедуру регистрации.