Я пытаюсь выяснить, что я делаю не так, как здесь, и пять часов утра, и я должен включить это сегодня в 9 часов утра, так что это моя последняя надежда прийти к вам, ребята.
Эта программа должна позволять пользователю вводить 5 целых, 7 чисел с плавающей запятой и 5 символов, которые входят в массивы, которые должны кодироваться с помощью шаблонов функций.Числовые данные должны быть отсортированы по пузырькам и усреднены.Это должно быть распечатано. Затем я должен сохранить массивы в файл .dat, извлечь данные из файла и еще раз вывести их.
Ошибки: среднее значение как-то неправильно записывается, поэтому вы получаетенеприятный случайный вывод памяти.В текстовый файл сохраняются только значения int, и я даже не знаю, как правильно извлечь и снова напечатать полученные значения.
Обновленный код с фиксированной функцией calc
#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;
//Load data to array from Keyboard.
template <class T>
void load(T *a,const int n)
{
for(int i=0;i<n;i++)
cin>>a[i];
}
//Calc and Print the Average for a numeric array.
template <class T>
void calc(T *a,const int n,float *avg)
{
float b=0;
for (int i=1;i<n;i++)
{
b+=a[i];
}
*avg=b/n;
cout<<"The Average is: "<<*avg<<endl;
//Does not work. Prints out a random block of memory.
//Tried a couple things and still get he same bug.
}
//Sort the data array in ascending order.
template <class T>
void sort(T *a,const int n)
{
float t;
for(int i=0;i<n-1;i++)
for(int j=0;j<n-1;j++)
if (a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
//Save the array data to a text file.
template <class T>
void get(T *a,const int n)
{
ofstream outfile("C:\array.dat", ios::out);
for(int i=0;i<n;i++)
outfile << a[i]<< endl;
outfile.close();
//Only saves the first array (The ints)
}
//Retrieve the array data from the text file.
template <class T>
void save(T *a,const int n)
{
ifstream infile("C:\array.dat", ios::in);
for(int i=0;i<n;i++)
{
infile>>a[i];
}
infile.close();
}
/*Output should include the average for each of the two numeric arrays
along with all three arrays being printed out in ascending order twice,
once before the text file is saved and once after the array is retrieved
from the text file*/
int main()
{
const int n1=5,n2=7,n3=5;
int a[n1];
float b[n2];
char c[n3];
float avg[3];
int i;
cout<<"Enter 5 integers"<<endl;
load(a,n1);
sort(a,n1);
calc(a,n1,avg);
cout<<"Enter 7 floats"<<endl;
load(b,n2);
sort(b,n2);
calc(b,n2,avg+1);
cout<<"Enter 5 strings"<<endl;
load(c,n3);
cin.ignore(20, '\n');
sort(c,n3);
cout << endl;
cout<<"Output:"<<endl;
cout<<"The Integer array:" << endl;
for (i = 0; i < n1; i++)
cout << a[i] << " ";
cout << endl;
cout<<"The Float array:" << endl;
for (i = 0; i < n2; i++)
cout << b[i] << " ";
cout << endl;
cout<<"The String array:" << endl;
for (i = 0; i < n3; i++)
cout << c[i] << " ";
cout << endl;
save(a,n1);
get(a,n1);
save(b,n2);
get(b,n2);
save(c,n3);
get(c,n3);
//Need to print the now returned values here.
cout << endl;
//cin.get();
system("PAUSE");
return 0;
}
Извините, если половина этого не имеет смысла.Я очень устал.