#include "stdafx.h"
#include <iostream> // подключаем стандартные библиотеки + библиотеку мат. функций.
#include <cmath>
#include <locale>
#include <cstdlib>
using namespace std;
template<class T>
class vector3d // класс трехмерного вектора
{
public:
vector3d();
~vector3d();
void SetVector(const char * const caption); // функция позволяет ввести координаты вектора
void display(const char * const caption); // функция выводящая вектор на экран
void summ(vector3d *vec1, vector3d *vec2); // получает вектор суммы
void razn(vector3d *vec1, vector3d *vec2); // получает вектор разности
void dlina(vector3d *vec1); // вычисляет длину вектора
void scalar(vector3d *vec1, vector3d *vec2); // скалярно умножает вектора
private:
T x, y, z; // сами координаты
};
template<class T>
vector3d<T>::vector3d() // конструктор класса
{
x = T(0);
y = T(0);
z = T(0);
}
template<class T>
vector3d<T>::~vector3d() // пустой деструктор
{
}
template<class T>
void vector3d<T>::SetVector(const char * const caption)
{
cout << caption << endl;
cout << "X = ";
cin >> x; // вводим координаты вектора
cout << "Y = ";
cin >> y;
cout << "Z = ";
cin >> z;
}
template<class T>
void vector3d<T>::summ(vector3d *vec1, vector3d *vec2)
{
x = vec1->x + vec2->x; // складываем координаты векторов
y = vec1->y + vec2->y;
z = vec1->z + vec2->z;
}
template<class T>
void vector3d<T>::razn(vector3d *vec1, vector3d *vec2)
{
x = vec1->x - vec2->x; // вычитаем координаты векторов
y = vec1->y - vec2->y;
z = vec1->z - vec2->z;
}
template<class T>
void vector3d<T>::dlina(vector3d *vec1)
{
cout << "Dlina vektora:" << endl;
// ниже мы вычисляем по фрмуле длину вектора
float u = sqrt((vec1->x * vec1->x) + (vec1->y * vec1->y) + (vec1->z * vec1->z));
cout << u << endl;
}
template<class T>
void vector3d<T>::scalar(vector3d *vec1, vector3d *vec2)
{
float dot = (vec1->x * vec2->x) + (vec1->y * vec2->y) + (vec1->z * vec2->z);
// строчка выше умножает скалярно два вектора
cout << "Rezultat skaliarnogo peremnozenia dvuh vektorov:" << endl
<< dot << endl;
}
template<class T>
void vector3d<T>::display(const char * const caption)
{
cout << caption << endl
<< "Vektor s koordinatami:" << endl
<< "X = " << x << endl
<< "Y = " << y << endl
<< "Z = " << z << endl;
}
int main(int argc, char *argv[])
{
locale::global(locale(""));
// обьявляем экземпляры класса, у нас 2 вектора для работы и один для результатов
vector3d<float> *vector1 = new vector3d<float>;
vector3d<float> *vector2 = new vector3d<float>;
vector3d<float> *result_vector = new vector3d<float>;
int p; // переменная для выбора в меню далее само меню
while (true)
{
cout << "------------------------MENU-------------------------" << endl
<< "\t1 - Slozenie dvuh vektorov" << endl
<< "\t2 - Raznostb dvuh vektorov" << endl
<< "\t3 - Vuchitatb dliny vektora" << endl
<< "\t4 - Skaliarnoe prozvedenie dvuh vektorov" << endl
<< "\t0 - Vuhod iz programmu" << endl
<< "-----------------------------------------------------" << endl;
cin >> p;
system("cls"); // очистим экран
switch (p) // смотрим что выбрали в меню и вызываем соответствующие функции
{
case 1:
vector1->SetVector("Vvedite koordinatu vektora 1:");
vector2->SetVector("Vvedite koordinatu vektora 2:");
result_vector->summ(vector1, vector2);
result_vector->display("-----------Resultat----------");
break;
case 2:
vector1->SetVector("Vvedite koordinatu vektora 1:");
vector2->SetVector("Vvedite koordinatu vektora 2:");
result_vector->razn(vector1, vector2);
result_vector->display("-----------Resultat----------");
break;
case 3:
vector1->SetVector("Vvedite koordinatu vektora:");
result_vector->dlina(vector1);
break;
case 4:
vector1->SetVector("Vvedite koordinatu vektora 1:");
vector2->SetVector("Vvedite koordinatu vektora 2:");
result_vector->scalar(vector1, vector2);
break;
case 0:
exit(0);
break;
}
}
system("PAUSE");
return EXIT_SUCCESS;
}
#include <locale>
#include <limits>
#include <iostream>
#include <conio.h>
using namespace std;
// Тип данных с которым будем работать
typedef double data_t;
template<class T>
class complex
{
public:
// Конструктор
complex<T>(T re = 0, T im = 0);
// Возвращает действительную часть
T re(void) const;
static T re(const complex<T>& val);
// Возвращает мнимую часть
T im(void) const;
static T im(const complex<T>& val);
// Оператор сложения
template<class Ty> friend complex<Ty> operator+(const complex<Ty>& val1, const complex<Ty>& val2);
complex<T> & operator+=(const complex<T>& val);
// Оператор вычитания
template<class Ty> friend complex<Ty> operator-(const complex<Ty>& val1, const complex<Ty>& val2);
complex<T> & operator-=(const complex<T>& val);
// Оператор умножения
template<class Ty> friend complex<Ty> operator*(const complex<Ty>& val1, const complex<Ty>& val2);
complex<T> & operator*=(const complex<T>& val);
// Операторы ввода/вывода
template<class Ty> friend ostream & operator<<(ostream& stream, const complex<Ty>& val);
template<class Ty> friend istream & operator>>(istream& stream, complex<Ty>& val);
private:
T _re;
T _im;
};
// Выбор пользователя в меню
enum user_choice
{
ADD,
SUB,
MUL,
EXIT
};
user_choice menu();
void add();
void sub();
void mul();
int main()
{
locale::global(locale(""));
while (true)
{
switch (menu())
{
case ADD:
add();
break;
case SUB:
sub();
break;
case MUL:
mul();
break;
case EXIT:
return 0;
}
}
#ifdef _WIN32
system("pause");
#endif
return 0;
}
// Меню
user_choice menu()
{
while (true)
{
cout << "Меню:" << endl
<< "1 - Сложение" << endl
<< "2 - Вычитание" << endl
<< "3 - Умножение" << endl
<< "0 - Выход" << endl
<< "Ваш выбор:";
int choice = _getch();
if (choice == 0 || choice == 0xE0)
{
_getch();
}
else
{
cout << static_cast<char> (choice) << endl;
switch (choice)
{
case '1':
return ADD;
case '2':
return SUB;
case '3':
return MUL;
case '0':
return EXIT;
}
}
cout << endl
<< "Будьте внимательней!" << endl;
}
}
// Ввод комплексного числа
complex<data_t> read_complex(const char* const msg)
{
while (true)
{
cout << msg;
complex<data_t> result;
cin >> result;
if (!cin.fail())
{
cin.ignore(numeric_limits<streamsize>::max(), '\n');
return result;
}
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Ошибочный ввод!" << endl
<< "Вводить надо в формате: re im" << endl;
}
}
// Сложение
void add()
{
cout << "Сложение двух комплексных чисел:" << endl;
complex<data_t> first = read_complex("Введите 1е число:"), second = read_complex("Введите 2е число:");
cout << "Сумма:" << first << " + " << second << " = " << first + second << endl;
}
// Вычитание
void sub()
{
cout << "Вычитание двух комплексных чисел:" << endl;
complex<data_t> first = read_complex("Введите 1е число:"), second = read_complex("Введите 2е число:");
cout << "Разница:" << first << " - " << second << " = " << first - second << endl;
}
// Умножение
void mul()
{
cout << "Умножение двух комплексных чисел:" << endl;
complex<data_t> first = read_complex("Введите 1е число:"), second = read_complex("Введите 2е число:");
cout << "Произведение:" << first << " * " << second << " = " << first * second << endl;
}
// Конструктор
template<class T>
inline complex<T>::complex(T re, T im)
: _re(re)
, _im(im)
{
}
// Оператор вывода в поток
// Выводит в формате (re+/-im)
template<class Ty>
ostream & operator<<(ostream& stream, const complex<Ty>& val)
{
stream << '(';
// Выводим действительную часть если re!=0 или im==0
if (val._re || !val._im)stream << val._re;
// im!=0
if (val._im)
{
// Сохраним флаги потока
ios_base::fmtflags flags = stream.flags();
// если re!=0 установим флаг вывода знака для положительных чисел
if (val._re)stream.setf(ios::showpos);
// Выводим мнимую часть
stream << val._im << 'i';
// Восстановим флаги
stream.flags(flags);
}
stream << ')';
return stream;
};
// Оператор ввода
template<class Ty>
istream & operator>>(istream& stream, complex<Ty>& val)
{
Ty re, im;
// Вводим
stream >> re >> im;
// Если все нормально
if (stream.good())
{
// Сохраним
val._re = re;
val._im = im;
}
return stream;
};
// Возвращает действительную часть
template<class T>
inline T complex<T>::re(void) const
{
return _re;
}
template<class T>
inline T complex<T>::re(const complex<T>& val)
{
return val._re;
}
// Возвращает мнимую часть
template<class T>
inline T complex<T>::im(void) const
{
return _im;
}
template<class T>
inline T complex<T>::im(const complex<T>& val)
{
return val._im;
}
// Оператор сложения
template<class Ty>
inline complex<Ty> operator+(const complex<Ty>& val1, const complex<Ty>& val2)
{
return complex<Ty > (val1._re + val2._re, val1._im + val2._im);
}
template<class T>
inline complex<T>& complex<T>::operator+=(const complex<T>& val)
{
_re += val._re;
_im += val._im;
return *this;
}
// Оператор вычитания
template<class Ty>
inline complex<Ty> operator-(const complex<Ty>& val1, const complex<Ty>& val2)
{
return complex<Ty > (val1._re - val2._re, val1._im - val2._im);
}
template<class T>
inline complex<T>& complex<T>::operator-=(const complex<T>& val)
{
_re -= val._re;
_im -= val._im;
return *this;
}
// Оператор умножения
template<class Ty>
complex<Ty> operator*(const complex<Ty>& val1, const complex<Ty>& val2)
{
return complex<Ty > (val1._re * val2._re - val1._im * val2._im, val1._re * val2._im + val1._im * val2._re);
}
template<class T>
complex<T>& complex<T>::operator*=(const complex<T>& val)
{
_re = _re * val._re - _im * val._im;
_im = _re * val._im + _im * val._re;
return *this;
}
Меню:
1 - Сложение
2 - Вычитание
3 - Умножение
0 - Выход
Ваш выбор:1
Сложение двух комплексных чисел:
Введите 1е число:a b
Ошибочный ввод!
Вводить надо в формате: re im
Введите 1е число:1 2
Введите 2е число:-1 5
Сумма:(1+2i) + (-1+5i) = (7i)
Меню:
1 - Сложение
2 - Вычитание
3 - Умножение
0 - Выход
Ваш выбор:2
Вычитание двух комплексных чисел:
Введите 1е число:0 5
Введите 2е число:1 5
Разница:(5i) - (1+5i) = (-1)
Меню:
1 - Сложение
2 - Вычитание
3 - Умножение
0 - Выход
Ваш выбор:3
Умножение двух комплексных чисел:
Введите 1е число:2 3
Введите 2е число:4 5
Произведение:(2+3i) * (4+5i) = (-7+22i)
Меню:
1 - Сложение
2 - Вычитание
3 - Умножение
0 - Выход
Ваш выбор:
$ g++ -o m m.cpp
m.cpp:278:60: предупреждение: no newline at end of file
m.cpp:41: ошибка: declaration of ‘class T’
m.cpp:15: ошибка: shadows template parm ‘class T’
m.cpp:44: ошибка: declaration of ‘class T’
m.cpp:15: ошибка: shadows template parm ‘class T’
m.cpp:47: ошибка: declaration of ‘class T’
m.cpp:15: ошибка: shadows template parm ‘class T’
m.cpp:50: ошибка: declaration of ‘class T’
m.cpp:15: ошибка: shadows template parm ‘class T’
m.cpp:53: ошибка: declaration of ‘class T’
m.cpp:15: ошибка: shadows template parm ‘class T’
m.cpp:55: ошибка: declaration of ‘class T’
m.cpp:15: ошибка: shadows template parm ‘class T’
m.cpp:57: ошибка: declaration of ‘class T’
m.cpp:15: ошибка: shadows template parm ‘class T’
m.cpp:58: ошибка: declaration of ‘class T’
m.cpp:15: ошибка: shadows template parm ‘class T’
--- m.cpp 2011-01-22 19:20:08.000000000 +0300
+++ m-fixed.cpp 2011-01-22 19:16:59.000000000 +0300
@@ -38,24 +38,24 @@
T arg(void) const;
static T arg(const complex<T>& val);
// Оператор сложения
- template<class T> friend complex<T> operator+(const complex<T>& val1,const complex<T>& val2);
+ template<class X> friend complex<X> operator+(const complex<X>& val1,const complex<X>& val2);
complex<T>& operator+=(const complex<T>& val);
// Оператор вычитания
- template<class T> friend complex<T> operator-(const complex<T>& val1,const complex<T>& val2);
+ template<class X> friend complex<X> operator-(const complex<X>& val1,const complex<X>& val2);
complex<T>& operator-=(const complex<T>& val);
// Оператор умножения
- template<class T> friend complex<T> operator*(const complex<T>& val1,const complex<T>& val2);
+ template<class X> friend complex<X> operator*(const complex<X>& val1,const complex<X>& val2);
complex<T>& operator*=(const complex<T>& val);
// Опрератор деления
- template<class T> friend complex<T> operator/(const complex<T>& val1,const complex<T>& val2);
+ template<class X> friend complex<X> operator/(const complex<X>& val1,const complex<X>& val2);
complex<T>& operator/=(const complex<T>& val);
// Возведение в степень
- template<class T> friend complex<T> pow(const complex<T>& val,T deg);
+ template<class X> friend complex<X> pow(const complex<X>& val,X deg);
// Извлечение квадратного корня
- template<class T> friend complex<T> sqrt(const complex<T>& val);
+ template<class X> friend complex<X> sqrt(const complex<X>& val);
// Операторы ввода/вывода
- template<class T> friend ostream& operator<<(ostream& stream,const complex<T>& val);
- template<class T> friend istream& operator>>(istream& stream,complex<T>& val);
+ template<class X> friend ostream& operator<<(ostream& stream,const complex<X>& val);
+ template<class X> friend istream& operator>>(istream& stream,complex<X>& val);
private:
T _re;
T _im;
template<class Ty>
ostream & operator<<(ostream& stream, const complex<Ty>& val)
{
stream << '(';
if (val._re || !val._im)stream << val._re;
if (val._im)
{
ios_base::fmtflags flags = stream.flags();
if (val._re)stream.setf(ios::showpos);
stream << val._im << 'i';
stream.flags(flags);
}
stream << ')';
return stream;
};
template<class Ty>
istream & operator>>(istream& stream, complex<Ty>& val)
{
Ty re, im;
stream >> re >> im;
if (stream.good())
{
val._re = re;
val._im = im;
}
return stream;
};
Если Вы уже зарегистрированы на Портале - войдите в систему, если Вы еще не регистрировались - пройдите простую процедуру регистрации.