Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Центр помощи > Помогите дописать программу(калькулятор компл. чис


Автор: egorletov 9.2.2006, 20:29
Ну нада написть в очень простом варианте такую программку .
1)подключаем файл типа Фаил.тхт такого вида = 15+i*10 -10+i*10 *5+i*5 +5+i*5 \4+i*2.0 ну и т.д
2)что бы програмка читала строку и выполняла умножение сложение деление отнимание) компл. чисел.
3)вот как я сделал загрузку входного файла + инизиаализация комп.числа , так же суммирование .

Код

//Main.cpp

#include <iostream>

#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include "Complex.h"

#include <fstream>
using namespace std;

ifstream f;
Double_Complex sa;
main ()
{


double ima[50];
double rea[50];
int h=50;
int t=1;
int y=1;
double imm[50];
double ree[50];
char opera;
  sa.indif(t,&rea[1],&ima[1]);
//cout<<opera<<endl;


sa.sum(y,&imm[0],&ree[0]);


cout<<"DOSTIGNYT KONETS FAILA"<<endl;

getch();


}



сомплеч.спп


Код

#include <math.h>
#include "Complex.h"
#include <conio.h>
#include <string>
#include <vector>
#include <fstream>
using namespace std;



double Double_Complex::indif(int &kol,double operand_1[1],double operand_2[1])
{
    ifstream f;
    f.open("file.txt");

    if(!f){
        cout<<"Error 1:open input file,imposseble"<<endl;
        exit(1);
    }
    

    char znak,i, mul;
int      g=0;
    do{
    
f>>operand_1[g]>>znak>>i>>mul>>operand_2[g];
//f>>oper;
if (znak!='+')
cout<<("Kompleksnoe thislo izmenino pod tip: a+i*b, !")<<endl;
if(znak=='-')
    znak='+';

cout<<g<<")"<<operand_1[g]<<znak<<i<<mul<<operand_2[g]<<endl  ;
g++;
} 
    while(!( f.eof()));
kol=g;
return kol,operand_1[g],operand_2[g];
}



double Double_Complex::sum(int &kol,double im[1],double re[1])
{

    char zna='+';
char ii='i';
char mu='*';

int r=0;
int e=0;
int g=0;
int ti=0;
int w=1;
int log=0;
char san;
double Real[50];
double Imaginer[50];
Imaginer[r]=0.0;
Real[r]=0.0;
indif(g,&re[0],&im[0]);
cout<<"\n"<<"kolitestvo kompleksnix tisel = "<<g<<"\n"<<endl;
     
do{

        Real[ti]=Real[ti]+re[e];
        cout<<e<<")"<<Real[ti]<<zna<<ii<<mu<<Imaginer[ti]<<endl;
        Imaginer[ti]=Imaginer[ti]+im[e];
 e++;
 }
 while (e!=g-0);
 cout<<r<<"\n Symma = "<<Real[ti]<<zna<<ii<<mu<<Imaginer[ti]<<endl ;


                    return Real[ti],Imaginer[ti];

}



сомплех.Х

Код

#ifndef __Complex_H
#define __Complex_H

#include <iostream>
#include <string>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>

#include <fstream>
using namespace std;

class Double_Complex
{
private: 
     
      double Im;
      double Re;
public:
double Double_Complex::indif(int &kol,double operand_1[50],double operand_2[50]);
double Double_Complex::sum(int &kol,double im[1],double re[1]);
   
 
};


#endif




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

Автор: cardinal 9.2.2006, 20:57
Цитата(egorletov @ 9.2.2006, 18:29 Найти цитируемый пост)

но все таки ответа я не получил

Я твоего вопроса так и не нашел... smile

Автор: egorletov 9.2.2006, 22:02

Создайте класс Complex для представления комплексных данных и инкапсулируйте в нём основные операции с комплексными данными.
По крайней мере, предусмотрите следующие методы:
• конструктор, с помощью которого можно инициализировать комплексное данное;
• метод, позволяющий задать произвольное значение комплексного данного;
• методы, обеспечивающие выполнение арифметических действий над комплексными данными (сложение, вычитание, умножение, деление, модуль);
• метод print, обеспечивающий печать комплексного данного на консоль или в любой файл;
• метод toString, обеспечивающий преобразование комплексного данного в строку символов.
Усовершенствуйте класс Complex, обеспечив реализацию следующей функциональности:
• Инициализация комплексного числа значением плавающего типа;
• Перегруженные арифметические операции для выполнения основных арифметических действий;
• Перегруженные операции >> и << для ввода и вывода комплексных данных (см. приложение II учебного пособия);
• Преобразование из типа Complex к типу double (когда возможно).
Продумайте как организовать обработку ошибок при выполнении некорректных операций с объектами класса Complex. Что это за некорректные операции?
Спроектируйте комплект тестирующих программ для проверки разработанного класса.
Используя и развивая определение класса Complex, спроектируйте набор классов для представления следующих абстракций:
• Список комплексных данных;
• Массив комплексных данных с контролем индексирования;
• Матрица комплексных данных . с контролем индексирования.
Напишите тестирующие программы, загружающие соответствующие контейнеры комплексных данных из файла, и обеспечивающие разнообразную обработку комплексных данных в рамках реализованной функциональности.

Автор: CPlusPlusFAN 10.2.2006, 04:38
Я только сегодня закончил примерно то же.

Только о выводе в файл (или куда ещё) я как-то не думал и не загонялся с переводом к double... Но добавлен флаг бесконечности.

(Основной упор сделан на перегрузку операторов, т.к. хотел закрепить этот материал)

Автор: egorletov 10.2.2006, 20:32
А ты не мог бы выложить здесь твоё работу , буду очень признателен

Автор: LPBOY 10.2.2006, 22:00
Цитата(egorletov @ 9.2.2006, 20:29 Найти цитируемый пост)

1)подключаем файл типа Фаил.тхт такого вида = 15+i*10 -10+i*10 *5+i*5 +5+i*5 \4+i*2.0 ну и т.д
2)что бы програмка читала строку и выполняла умножение сложение деление отнимание) компл. чисел.


Мне кажется ты не так понял задание:
Цитата(egorletov @ 9.2.2006, 22:02 Найти цитируемый пост)

Напишите тестирующие программы, загружающие соответствующие контейнеры комплексных данных из файла, и обеспечивающие разнообразную обработку комплексных данных в рамках реализованной функциональности.

Там не говорится, что в файлах должны содержаться выражения с комплексными числами (сложение, деление и т.д.). Я думаю, имелись в виду, файлы такого вида:
Код

1  3
4  2
3  6

(В каждой строке вещественная и мнимая части). Вот их нужно прочитать и уже в самой программе выполнить какие-то действия над ними. В общем уточни у препода, кажется, ты делаешь лишнюю работу...

Автор: LPBOY 10.2.2006, 23:47
Цитата(egorletov @ 9.2.2006, 20:29 Найти цитируемый пост)

буду очень благодарен если вы мне поможете дописать мой проект

egorletov, вот частично реализованный класс Complex (надеюсь нигде не ошибся smile ). Остальное сделаешь сам. smile

Complex.h
Код

#include <cmath>
#include <iostream>
#include <sstream>

class Complex
{
private:
    double re_;
    double im_;
public:
    Complex()
    :re_(0), im_(0)
    {
    }
    Complex(double re, double im)
    :re_(re), im_(im)
    {
    }
    double real()
    {
        return re_;
    }
    double imag()
    {
        return im_;
    }
    void real(double re)
    {
        re_ = re;
    }
    void imag(double im)
    {
        im_ = im;
    }
    friend
    Complex operator+(const Complex& left, const Complex& right)
    {
        return Complex(left.re_ + right.re_, left.im_ + right.im_);
    }
    friend
    Complex operator-(const Complex& left, const Complex& right)
    {
        return Complex(left.re_ - right.re_, left.im_ - right.im_);
    }
    //(x + iy)*(u + iv) == (xu – yv) + i(xv + yu)
    friend
    Complex operator*(const Complex& left, const Complex& right)
    {
        return Complex(left.re_*right.re_ - left.im_*right.im_, left.re_*right.im_ + left.im_*right.re_);
    }
    //(x + iy)/(u + iv) == ((xu + yv) + i(–xv + yu))/(u^2 + v^2)
    friend
    Complex operator/(const Complex& l, const Complex& r)
    {
        if(r.re_ == 0 && r.im_ == 0) throw std::runtime_error("division by zero");
        return Complex((l.re_*r.re_ + l.im_*r.im_)/(r.re_*r.re_ + r.im_*r.im_),
                       (l.im_*r.re_ - l.re_*r.im_)/(r.re_*r.re_ + r.im_*r.im_)
                      );
    }
    double abs()
    {
        return sqrt(re_*re_ + im_*im_);
    }
    friend
    std::ostream& operator<<(std::ostream& os, const Complex& c)
    {
        return os << '(' << c.re_ << ',' << c.im_ << ')' << '\n';
    }
    void print(std::ostream& os)
    {
        os << *this;
    }
    friend
    std::istream& operator>>(std::istream& is, Complex& c)
    {
        return is >> c.re_ >> c.im_;
    }
    std::string toString()
    {
        std::ostringstream oss;
        oss << '(' << re_ << ',' << im_ << ')';
        return std::string(oss.str());
    }
};


main.cpp
Код

#include <iostream>
#include <fstream>
#include "Complex.h"

int main()
{
    Complex c1(1.0, 2.0), c2, c3(7.0, 4.0);
    std::ofstream file("d:\\file.txt");
    std::cout << c1 << c2 << c3;
    file << c1 << c2 << c3;
    c1.real(5.0);
    c2.imag(6.0);
    c2 = c1 + c3;
    c1 = c2 - c3;
    c3 = c1 * c2;
    c1 = c2 / c3;
    c1.print(std::cout);
    c2.print(file);
    std::string str = c1.toString();
    std::cout << str << '\n';
    std::cout << c3.abs() << '\n';
    return 0;
}

Работало на VC7.1

Автор: CPlusPlusFAN 11.2.2006, 02:02
egorletov, посмотри, может что найдёшь:

Код

#ifndef _NumberH
#define _NumberH

#include <Math.h>
#include <stdlib.h>
#include <SysUtils.hpp>

class Numeric
{
float real,imag;
bool infinity;
public:
Numeric(float reall,float imagg):real(reall),imag(imagg),infinity(false){}
Numeric(Numeric& copy):real(copy.real),imag(copy.imag),infinity(copy.infinity){}
float Real(void){return real;}
float Imag(void){return imag;}
void SetReal(float reall){real=reall;}
void SetImag(float imagg){imag=imagg;}
bool Infinity(void){return infinity;}
Numeric operator =(Numeric a);
Numeric operator +(Numeric a);
Numeric operator -(Numeric a);
Numeric operator *(Numeric a);
Numeric operator /(Numeric a);
Numeric operator +=(Numeric a);
Numeric operator -=(Numeric a);
Numeric operator *=(Numeric a);
Numeric operator /=(Numeric a);
Numeric operator <<(Numeric a);//trunc
Numeric operator <<=(Numeric a);//trunc
Numeric operator %(Numeric a);//round
Numeric operator %=(Numeric a);//round
Numeric operator ^(float a);//power
Numeric operator ^=(float a);//power
float operator !(void);//module
friend Numeric operator -(Numeric a);//negative
bool operator ==(Numeric a);
bool operator !=(Numeric a);
operator char*(void);
~Numeric(){}
};

float Numeric::operator !(void)
{
return sqrt(real*real+imag*imag);
}

Numeric Numeric::operator =(Numeric a)
{
real=a.real;
imag=a.imag;
infinity=a.infinity;
return *this;
}

Numeric operator -(Numeric a)
{
a.real=-a.real;
a.imag=-a.imag;
return a;
}

Numeric Numeric::operator +(Numeric a)
{
Numeric temp=*this;
if (temp.infinity||a.infinity)
{
temp.infinity=true;
temp.imag=temp.real=0;
}
else
{
temp.real+=a.real;
temp.imag+=a.imag;
}
return temp;
}

Numeric Numeric::operator -(Numeric a)
{
Numeric temp=*this;
temp=temp+(-a);
return temp;
}

Numeric Numeric::operator *(Numeric a)
{
Numeric temp=*this;
if (temp.infinity||a.infinity)
{
temp.infinity=true;
temp.imag=temp.real=0;
}
else
{
temp.real=real*a.real-imag*a.imag;
temp.imag=real*a.imag+imag*a.real;
}
return temp;
}
/*
float Numeric::Abs(void)
{
return sqrt(real*real+real*real);
}*/

Numeric Numeric::operator /(Numeric a)
{
Numeric temp=*this,A=a;
float mod=!A;
if (temp.infinity||A.infinity||!mod)
{
temp.infinity=true;
temp.imag=temp.real=0;
}
else
{
A.imag=-A.imag;
temp*=A;
temp.real/=mod;
temp.imag/=mod;
}
return temp;
}

Numeric Numeric::operator +=(Numeric a)
{
(*this)=(*this)+a;
return *this;
}

Numeric Numeric::operator -=(Numeric a)
{
(*this)+=-a;
return *this;
}

Numeric Numeric::operator *=(Numeric a)
{
(*this)=(*this)*a;
return *this;
}

Numeric Numeric::operator /=(Numeric a)
{
(*this)=(*this)/a;
return *this;
}

Numeric Numeric::operator <<(Numeric a)
{
Numeric temp=*this;
if (!temp.infinity)
{
temp/=a;
temp.real=floor(temp.real);
temp.imag=floor(temp.imag);
}
return temp;
}

Numeric Numeric::operator <<=(Numeric a)
{
(*this)=(*this)<<a;
return *this;
}

Numeric Numeric::operator %(Numeric a)
{
Numeric temp=*this;
if (!temp.infinity)
{
temp.real+=0.5;
temp.imag+=0.5;
temp/=a;
temp.real+=0.5;
temp.imag+=0.5;
temp.real=floor(temp.real);
temp.imag=floor(temp.imag);
}
return temp;
}

Numeric Numeric::operator %=(Numeric a)
{
(*this)=(*this)%a;
return *this;
}

Numeric Numeric::operator ^(float a)
{
const float pi=3.141592653589793;
Numeric temp=*this;
float A=!temp;
if (!A&&a<=0||temp.infinity)
{
temp.infinity=true;
temp.imag=temp.real=0;
}
else
{
float c=acos(temp.real/A),s;
c*=a-2*pi*floor(a/(2*pi));
c=cos(c);
A=pow(A,a);
s=sqrt(1-c*c);
temp.real=A*c;
temp.imag=A*s;
}
return temp;
}

Numeric Numeric::operator ^=(float a)
{
(*this)=(*this)^a;
return *this;
}

bool Numeric::operator ==(Numeric a)
{
return this->real==a.real&&this->imag==a.imag;
}

bool Numeric::operator !=(Numeric a)
{
return !((*this)==a);
}

Numeric::operator char*(void)
{
Numeric temp=*this;
AnsiString buf;
buf=FloatToStr(temp.real);
if (temp.imag>=0) buf=buf+'+';
buf=buf+FloatToStr(temp.imag);
buf=buf+'i';
char *res=buf.c_str();
return res;
}

#endif

Автор: egorletov 14.2.2006, 13:20
Ага пасибки , надо просмотреть обдумать.

Автор: egorletov 15.2.2006, 21:21
CPlusPlusFAN а не мог бы ты Main.cpp описать, а то что не очень я понял всей проги.. то чнее как с ней работать, наверное из-за каких то пробелов в обучение..

Автор: egorletov 16.2.2006, 21:40
smile

Автор: Fixin 16.2.2006, 22:17
Модератор: В данном разделе запрещено поднимать темы (Правила)
Напиши ему в PM. Пока прощаю.

Автор: Akina 17.2.2006, 10:38
egorletov
В приведенной строке НЕТ необходимости выполнять операции с комплексными числами. Почитайте справку о приоритете арифметических операций. Были бы скобки - другой вопрос...

Но если ты всерьез намерен заняться калькулятором - лучше измени формат исходных данных.
Вот пример возможного исходного формата (после ";" комментарии):

A 10 5i ; A=(10+5i)
B 2 -3i ; B=(2-3i)
C -4 -6.2i ; C=(-4-6.2i)
D 2i ; D=(0+2i)
E A + B ; E=A+B
A E * C ; A=E*C
B D / C ; B=D/C
? A ; Вывести A на экран
?? B c:\b.txt ; вывести В в файл




Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)