Шаблоны функций в C ++ Проблемы - PullRequest
1 голос
/ 29 февраля 2012

Я пытаюсь выяснить, что я делаю не так, как здесь, и пять часов утра, и я должен включить это сегодня в 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;
}

Извините, если половина этого не имеет смысла.Я очень устал.

Ответы [ 3 ]

1 голос
/ 29 февраля 2012

Для среднего:

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[n]=b/n;
    cout<<"The Average is: "<<avg[4]<<endl; 
    //Does not work. Prints out a random block of memory. 
    //Tried a couple things and still get he same bug.

}

вам не нужен массив средних, вам просто нужно одно среднее.

agv[n] = b / n; //assigns to the the n'th elemement of an array called avg.

попробуйте вместо этого:

*avg = b/n

А для распечатки просто '* avg'.

Когда вы звоните calc, попробуйте:

float avg1;
calc(b,n4,&avg1);

Когда вы видите & и *, читайте их следующим образом:

& address of
* contents of address
0 голосов
/ 29 февраля 2012

Когда вы открываете файл, вам необходимо указать приложение ios:, которое добавляется к существующему файлу. Без этого каждый раз, когда вы пишете в файл, все, что существовало в нем ранее, будет выбрасываться.

ios::out | ios::app

Итак, сначала напишите, просто используйте ios :: out, после этого включите ios :: app

0 голосов
/ 29 февраля 2012

вам нужно только три средних, одно для 5-ти целых, одно для 7-ми чисел и одно для 5-ти символов.

float avg[4];   // should be: float avg[3];

Вы, похоже, передаете неправильные параметры каждой из функций calc. Когда вы вызываете calc для ints, используйте:

calc(a,n1,avg);

для поплавков:

calc(b,n2,avg+1);

для символов:

calc(c,n3,avg+2);

N4 = 2; не имеет отношения ни к чему, вы можете удалить n4.

...