/*
Номер и вид работы: Задание №2 Классы
Название работы: Классы
Ф.И.О.: Бойко Павел Николаевич
Номер зачетной книжки: ИСз20-248
Группа: ИСз-208
Вариант: №8
*/
/*
Условие задания:
1). Составить описание класса для объектов-векторов, задаваемых
координатами концов в трехмерном пространстве. Обеспечить операции
сложения и вычитания векторов с получением нового вектора (суммы или
разности), вычисления скалярного произведения двух векторов, длины
вектора, косинуса угла между векторами?
2).Написать программу, демонстрирующую работу с этим классом.
Программа должна содержать меню, позволяющее осуществить проверку всех
методов класса?
*/
#include <iostream> // подключаем стандартные библиотеки + библиотеку мат. функций.
#include <cmath> /*Включает заголовок стандартной библиотеки C <math.h> и добавляет связанные имена в std пространство имен. */
#include <locale> /*Две функции, которые изменяют глобальные настройки locale, - это std::setlocale и std::locale::global . Все будущие операции ввода-вывода C и C++*/
#include <cstdlib> /*Заголовок: <cstdlib>. Пространство имен: std. Пространство имен и макросы.*/

using namespace std; /*сообщает компилятору, что мы хотим использовать всё, что находится в пространстве имен std*/

template<class T> /*Вы должны включить 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); // скалярно умножает вектора
    void cosinus(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 << "ДЛИНА ВЕКТОРА:" << 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 << "РЕЗУЛЬТАТ СКАЛЯРНОГО ПРОИЗВЕДЕНИЯ ВЕКТОРОВ:" << endl
            << dot << endl;
}

template<class T>
void vector3d<T>::cosinus(vector3d *vec1, vector3d *vec2)
{
    float dot = (vec1->x * vec2->x) + (vec1->y * vec2->y) + (vec1->z * vec2->z);
    float u = sqrt((vec1->x * vec1->x) + (vec1->y * vec1->y) + (vec1->z * vec1->z));
    float u2 = sqrt((vec2->x * vec2->x) + (vec2->y * vec2->y) + (vec2->z * vec2->z));
    // по формуле находим косинус угла между векторами
    float cos = (dot / (u * u2));

    cout << "КОСИНУС УГЛА МЕЖДУ ВЕКТОРАМИ:" << endl
            << cos << endl;
}

template<class T>
void vector3d<T>::display(const char * const caption)
{
    cout << caption << endl
            << "Вектор с координатами:" << 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 << "------------------------МЕНЮ-------------------------" << endl
                << "\t1 - Сложение двух векторов" << endl
                << "\t2 - Разность двух векторов" << endl
                << "\t3 - Высчитать длину вектра" << endl
                << "\t4 - Скалярное произведение векторов" << endl
                << "\t5 - Косинус угла между векторами" << endl
                << "\t0 - Выход из программы" << endl
                << "-----------------------------------------------------" << endl;

        cin >> p;
        system("cls"); // очистим экран

        switch (p) // смотрим что выбрали в меню и вызываем соответствующие функции
        {
        case 1:
            vector1->SetVector("Введите координаты вектора 1:");
            vector2->SetVector("Введите координаты вектора 2:");
            result_vector->summ(vector1, vector2);
            result_vector->display("-----------РЕЗУЛЬТАТ----------");
            break;
        case 2:
            vector1->SetVector("Введите координаты вектора 1:");
            vector2->SetVector("Введите координаты вектора 2:");
            result_vector->razn(vector1, vector2);
            result_vector->display("-----------РЕЗУЛЬТАТ----------");
            break;
        case 3:
            vector1->SetVector("Введите координаты вектора:");
            result_vector->dlina(vector1);
            break;
        case 4:
            vector1->SetVector("Введите координаты вектора 1:");
            vector2->SetVector("Введите координаты вектора 2:");
            result_vector->scalar(vector1, vector2);
            break;
        case 5:
            vector1->SetVector("Введите координаты вектора 1:");
            vector2->SetVector("Введите координаты вектора 2:");
            result_vector->cosinus(vector1, vector2);
            break;
        case 0:
            exit(0);
            break;
        }
    }

    system("PAUSE");
    return EXIT_SUCCESS;
} 

C++ Online Compiler

Write, Run & Share C++ code online using OneCompiler's C++ online compiler for free. It's one of the robust, feature-rich online compilers for C++ language, running on the latest version 17. Getting started with the OneCompiler's C++ compiler is simple and pretty fast. The editor shows sample boilerplate code when you choose language as C++ and start coding!

Read inputs from stdin

OneCompiler's C++ online compiler supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample program which takes name as input and print your name with hello.

#include <iostream>
#include <string>
using namespace std;

int main() 
{
    string name;
    cout << "Enter name:";
    getline (cin, name);
    cout << "Hello " << name;
    return 0;
}

About C++

C++ is a widely used middle-level programming language.

  • Supports different platforms like Windows, various Linux flavours, MacOS etc
  • C++ supports OOPS concepts like Inheritance, Polymorphism, Encapsulation and Abstraction.
  • Case-sensitive
  • C++ is a compiler based language
  • C++ supports structured programming language
  • C++ provides alot of inbuilt functions and also supports dynamic memory allocation.
  • Like C, C++ also allows you to play with memory using Pointers.

Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition If-Else is used.

if(conditional-expression) {
   //code
}
else {
   //code
}

You can also use if-else for nested Ifs and If-Else-If ladder when multiple conditions are to be performed on a single variable.

2. Switch:

Switch is an alternative to If-Else-If ladder.

switch(conditional-expression){    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
......    
    
default:     
 code to be executed when all the above cases are not matched;    
} 

3. For:

For loop is used to iterate a set of statements based on a condition.

for(Initialization; Condition; Increment/decrement){  
  //code  
} 

4. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while (condition) {  
// code 
}  

5. Do-While:

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {  
 // code 
} while (condition); 

Functions

Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increases re-usuability and modularity. Function gets run only when it is called.

How to declare a Function:

return_type function_name(parameters);

How to call a Function:

function_name (parameters)

How to define a Function:

return_type function_name(parameters) {  
 // code
}