Компьютерный форум OSzone.net  

Компьютерный форум OSzone.net (http://forum.oszone.net/index.php)
-   Программирование и базы данных (http://forum.oszone.net/forumdisplay.php?f=21)
-   -   Помогите пожалуйста переделать код с С++ на С! (http://forum.oszone.net/showthread.php?t=301670)

jdk 25-06-2015 17:57 2522456

Помогите пожалуйста переделать код с С++ на С!
 
Задание :

Создать программу, генерирующую систему логических функций с заданными параметрами n - число входных переменных, m - число функций.
В соответствии с заданным чмслом генерируется (2 ** n) входных комбинаций и каждой входной комбинации по индивидуальному заданию присваиваится одна из (2 ** m) выходных комбинаций (начиная с комбинации все нули) в циклической последовательности.
Записать сгенерированную систему логических функций в виде файла.
При создании функции предусмотреть возможность задания параметров m, n в качестве аргументов командной строки.
Генерация выходных комбинаций в порядке возрастания с шагом 1.

Код на С++:

Код:

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <cstring>

using namespace std;

class Logfunc{
        private:
                int _n; // the number of input variables
                int _m; // the number of functions
                int _step; // step
                unsigned int _c; // the number of rows in the table
                unsigned int* func; // generated function
                void generate(); // function generation
                bool* tobool(unsigned int p, int n); // transfer of an integer to an array of booleans
               
        public:
                Logfunc(int n=3, int m=2, int step=2); // the constructor
                ~Logfunc(); // the destructor
                bool* calc(bool* params); // Evaluation of the function
                void write(char* filename); // write dates to file
};

// class constructor
Logfunc::Logfunc(int n, int m, int step): _n(n), _m(m), _step(step){
        generate(); // generate function
}
       
// destructor         
        Logfunc::~Logfunc(){
                free (func); // make free memory from the table
}

// function generator
void Logfunc::generate(){
        _c=1 << _n; // rows quantity of table(2**n)
        func=(unsigned int*)malloc(_c * sizeof(unsigned int)); // allocates memory for the table
        int max=1<<_m; // maximum decimal value of the output combinations(2**m)
        int r=(_step>=0)?0:max-1; //Function result for the first row in the table
        for (unsigned int i=0;i<_c;i++){
                func[i]=r; //write value in the table
                r+=_step; //increase value for the next step
                if(r>=max) // cycle for the succession increasing
                        r=0;
                if(r<0) // cycle for the succession decreasing
                        r=max-1;
        }
}

//transfer from an integer to an array of booleans
bool* Logfunc::tobool(unsigned int p, int n){
        bool* r=(bool*)malloc(n * sizeof(bool)); // allocates memory for an answer
        memset(r, 0, n * sizeof(bool)); // fills an array by 0
        int i=n;
        while (p>0 && i>0){
                bool b=p%2; // determine the value of the last bit
                p/=2; // seperate last bit
                r[--i]=b; // write bit value to an array of result       
        }
        return r;
}

// calculation of the values of function
bool* Logfunc::calc(bool* params){
        unsigned int ind=0;
        for(int i=0; i<_n; i++) // define line number in the table
                ind=(ind<<1)+params[i];
        unsigned int r=func[ind]; // define function value
        return tobool(r, _m);
}

// write result to file
void Logfunc::write(char* filename){
        ofstream fout(filename); // create file
        for(unsigned int i=0; i<_c; i++){ // We go through all the rows
                bool* p=tobool(i,_n); // We get a list of Boolean values
                bool* r=calc(p); // We calculate the value of the function
                for(int j=0;j<_n;j++)
                        fout<<p[j]?1:0; // displays a list of variables
                fout<<" "; // separation gap
                for(int j=0; j<_m; j++)
                        fout<<r[j]?1:0; // displays a list of variables
                fout<<endl; //displays end of row
                free(p); //free memory
                free(r); //free memory
        }
        fout.close(); // close file
}

int main()
{
        int step = 1;
        int n, m;
        cout<<"The number of input variables: ";
        cin>>n;
        if(n<1 || n>28){
                cout<<"Input error"<<endl;
                system("pause");
                return 1;
        }
        cout<<"Number of functions m : ";
        cin>>m;
                if(m<1 || m>32){
                cout<<"Input error"<<endl;
                system("pause");
                return 1;
        }       
       
        Logfunc f(n, m, step); //create function
        f.write("output.txt");
        cout<<"Result is saved to file - output.txt"<<endl;
        system("pause"); //delay before programm closing
        return 0;       
}


jdk 25-06-2015 19:06 2522471

Помогите пожалуйста

lxa85 26-06-2015 00:02 2522588

jdk, скомпилировал я приложение в VS. В output мне записало
Код:

000 000
001 001
010 010
011 011
100 100
101 101
110 110
111 111

Вопрос. Что не так?
Иными словами: я задание перечитал раза 3 - ничего не понял!

Iska 26-06-2015 00:24 2522593

Цитата:

Цитата lxa85
Вопрос. Что не так?
Иными словами: я задание перечитал раза 3 - ничего не понял! »

Всё не так :):
Цитата:

Цитата jdk
переделать код с С++ на С! »

т.е. — «кто бы сделал».


Время: 09:16.

Время: 09:16.
© OSzone.net 2001-