Напиши модульную программу на языке С++
Jump to turn (6)
- User
Напиши модульную программу на языке С++
- Assistant
Напиши модульную программу на языке С++
Конечно! Ниже приведён пример простой модульной программы на языке C++. Эта программа реализует базовые операции над числами: сложение, вычитание, умножение и деление. Мы организуем код в несколько модулей.
/my_calculator/
├── main.cpp
├── calculator.h
├── calculator.cpp
#ifndef CALCULATOR_H
#define CALCULATOR_H
class Calculator {
public:
static double add(double a, double b);
static double subtract(double a, double b);
static double multiply(double a, double b);
static double divide(double a, double b);
};
#endif // CALCULATOR_H
#include "calculator.h"
#include <stdexcept>
double Calculator::add(double a, double b) {
return a + b;
}
double Calculator::subtract(double a, double b) {
return a - b;
}
double Calculator::multiply(double a, double b) {
return a * b;
}
double Calculator::divide(double a, double b) {
if (b == 0) {
throw std::invalid_argument("Division by zero is not allowed.");
}
return a / b;
}
#include <iostream>
#include "calculator.h"
int main() {
double num1, num2;
char op;
std::cout << "Enter first number: ";
std::cin >> num1;
std::cout << "Enter an operator (+, -, *, /): ";
std::cin >> op;
std::cout << "Enter second number: ";
std::cin >> num2;
try {
double result;
switch (op) {
case '+':
result = Calculator::add(num1, num2);
break;
case '-':
result = Calculator::subtract(num1, num2);
break;
case '*':
result = Calculator::multiply(num1, num2);
break;
case '/':
result = Calculator::divide(num1, num2);
break;
default:
std::cout << "Invalid operator!" << std::endl;
return 1;
}
std::cout << "Result: " << result << std::endl;
} catch (const std::invalid_argument& e) {
std::cout << "Error: " << e.what() << std::endl;
}
return 0;
}
Чтобы скомпилировать эту программу, выполните следующие команды в командной строке:
g++ -c calculator.cpp
g++ -c main.cpp
g++ -o calculator main.o calculator.o
Запустите программу с помощью команды:
./calculator
После этого программа попросит ввести два числа и оператор, и выведет результат соответствующей операции.
Напиши модульную программу на языке С++
Конечно! Давайте создадим небольшую модульную программу на языке C++, которая реализует простую библиотеку для работы с векторами. Программа будет содержать следующие функции: добавление элемента в вектор, удаление элемента и вывод содержимого вектора.
/my_vector_program/
├── main.cpp
├── vector_utils.h
├── vector_utils.cpp
#ifndef VECTOR_UTILS_H
#define VECTOR_UTILS_H
#include <vector>
class VectorUtils {
public:
void addElement(int element);
void removeElement(int element);
void displayElements() const;
private:
std::vector<int> elements;
};
#endif // VECTOR_UTILS_H
#include <iostream>
#include "vector_utils.h"
void VectorUtils::addElement(int element) {
elements.push_back(element);
}
void VectorUtils::removeElement(int element) {
auto it = std::remove(elements.begin(), elements.end(), element);
if (it != elements.end()) {
elements.erase(it, elements.end());
} else {
std::cout << "Element " << element << " not found." << std::endl;
}
}
void VectorUtils::displayElements() const {
std::cout << "Elements in vector: ";
for (int el : elements) {
std::cout << el << " ";
}
std::cout << std::endl;
}
Напиши модульную программу на языке С++
Конечно! Давайте создадим простой пример модульной программы на языке C++, которая реализует систему управления книгами в библиотеке. Мы создадим модули для работы с книгами, используя классы и стандартные контейнеры.
/library_system/
├── main.cpp
├── book.h
├── book.cpp
├── library.h
├── library.cpp
#ifndef BOOK_H
#define BOOK_H
#include <string>
class Book {
public:
Book(const std::string& title, const std::string& author);
std::string getTitle() const;
std::string getAuthor() const;
private:
std::string title;
std::string author;
};
#endif // BOOK_H
#include "book.h"
Book::Book(const std::string& title, const std::string& author)
: title(title), author(author) {}
std::string Book::getTitle() const {
return title;
}
std::string Book::getAuthor() const {
return author;
}
#ifndef LIBRARY_H
#define LIBRARY_H
#include <vector>
#include "book.h"
class Library {
public:
void addBook(const Book& book);
void displayBooks() const;
private:
std::vector<Book> books;
};
#endif // LIBRARY_H
#include "library.h"
#include <iostream>
void Library::addBook(const Book& book) {
books.push_back(book);
}
void Library::displayBooks() const {
std::cout << "Books in library:\n";
for (const auto& book : books) {
std::cout << "Title: " << book.getTitle() << ", Author: " << book.getAuthor() << std::endl;
}
}
Напиши модульную программу на языке С++
Конечно! Давайте создадим модульную программу на языке C++, которая будет реализовывать простую систему управления студентами. Эта система позволит добавлять студентов, отображать их список и искать студентов по имени.
/student_management/
├── main.cpp
├── student.h
├── student.cpp
├── student_management.h
├── student_management.cpp
#ifndef STUDENT_H
#define STUDENT_H
#include <string>
class Student {
public:
Student(const std::string& name, int age);
std::string getName() const;
int getAge() const;
private:
std::string name;
int age;
};
#endif // STUDENT_H
#include "student.h"
Student::Student(const std::string& name, int age) : name(name), age(age) {}
std::string Student::getName() const {
return name;
}
int Student::getAge() const {
return age;
}
#ifndef STUDENT_MANAGEMENT_H
#define STUDENT_MANAGEMENT_H
#include <vector>
#include "student.h"
class StudentManagement {
public:
void addStudent(const Student& student);
void displayStudents() const;
void findStudentByName(const std::string& name) const;
private:
std::vector<Student> students;
};
#endif // STUDENT_MANAGEMENT_H
Напиши модульную программу на языке С++
Давайте создадим простую модульную программу на C++, которая будет моделировать систему учета банковских счетов. В этой программе будут реализованы следующие функции:
/bank_account_system/
├── main.cpp
├── account.h
├── account.cpp
├── bank.h
├── bank.cpp
#ifndef ACCOUNT_H
#define ACCOUNT_H
#include <string>
class Account {
public:
Account(const std::string& owner, double initial_balance);
void deposit(double amount);
void withdraw(double amount);
double getBalance() const;
std::string getOwner() const;
private:
std::string owner;
double balance;
};
#endif // ACCOUNT_H
#include "account.h"
#include <stdexcept>
Account::Account(const std::string& owner, double initial_balance)
: owner(owner), balance(initial_balance) {}
void Account::deposit(double amount) {
if (amount <= 0) {
throw std::invalid_argument("Deposit amount must be positive.");
}
balance += amount;
}
void Account::withdraw(double amount) {
if (amount <= 0) {
throw std::invalid_argument("Withdrawal amount must be positive.");
}
if (amount > balance) {
throw std::runtime_error("Insufficient funds.");
}
balance -= amount;
}
double Account::getBalance() const {
return balance;
}
std::string Account::getOwner() const {
return owner;
}
Напиши для кода выше таблицу операторов, операндов и их количество вхождения. Операторы и операнды раздели на 2 таблицы. Учитывай условия, приведенные ниже. Условия:
На основе приведенного кода программы C++ для управления банковскими счетами, я проанализирую его и соберу таблицы операторов и операндов с учетом ваших условий.
| Оператор | Количество вхождений |
|---|---|
+ | 4 |
- | 5 |
* | 2 |
/ | 0 |
= | 15 |
( ) | 15 |
{ } | 9 |
; | 14 |
if | 4 |
else | 2 |
for | 1 |
while | 2 |
switch | 1 |
case | 1 |
return | 1 |
default | 1 |
-> | 0 |
. | 0 |
[] | 0 |
: | 1 |
, | 6 |
| Операнд | Количество вхождений |
|---|---|
owner | 6 |
amount | 5 |
initial_balance | 1 |
balance | 4 |
Account | 3 |
Not yet included in a published release.
#include <iostream>
#include "vector_utils.h"
int main() {
VectorUtils vectorUtils;
int choice, element;
do {
std::cout << "Menu:\n";
std::cout << "1. Add Element\n";
std::cout << "2. Remove Element\n";
std::cout << "3. Display Elements\n";
std::cout << "4. Exit\n";
std::cout << "Choose an option: ";
std::cin >> choice;
switch (choice) {
case 1:
std::cout << "Enter element to add: ";
std::cin >> element;
vectorUtils.addElement(element);
break;
case 2:
std::cout << "Enter element to remove: ";
std::cin >> element;
vectorUtils.removeElement(element);
break;
case 3:
vectorUtils.displayElements();
break;
case 4:
std::cout << "Exiting program." << std::endl;
break;
default:
std::cout << "Invalid choice! Please try again." << std::endl;
}
} while (choice != 4);
return 0;
}
Чтобы скомпилировать эту программу, выполните следующие команды в командной строке:
g++ -c vector_utils.cpp
g++ -c main.cpp
g++ -o vector_program main.o vector_utils.o
Запустите программу с помощью команды:
./vector_program
Это простой пример модульной программы на C++, и его можно расширять и улучшать по мере необходимости.
#include <iostream>
#include "library.h"
int main() {
Library library;
int choice;
std::string title, author;
do {
std::cout << "Menu:\n";
std::cout << "1. Add Book\n";
std::cout << "2. Display Books\n";
std::cout << "3. Exit\n";
std::cout << "Choose an option: ";
std::cin >> choice;
switch (choice) {
case 1:
std::cout << "Enter book title: ";
std::cin.ignore(); // Clear the input buffer
std::getline(std::cin, title);
std::cout << "Enter book author: ";
std::getline(std::cin, author);
library.addBook(Book(title, author));
break;
case 2:
library.displayBooks();
break;
case 3:
std::cout << "Exiting program." << std::endl;
break;
default:
std::cout << "Invalid choice! Please try again." << std::endl;
}
} while (choice != 3);
return 0;
}
Чтобы скомпилировать эту программу, выполните следующие команды в командной строке:
g++ -c book.cpp
g++ -c library.cpp
g++ -c main.cpp
g++ -o library_system main.o book.o library.o
Запустите программу с помощью команды:
./library_system
Этот пример демонстрирует основные принципы модульного программирования в C++. Вы можете расширять программу, добавляя дополнительные функции, такие как удаление книг, поиск и т. д.
#include "student_management.h"
#include <iostream>
void StudentManagement::addStudent(const Student& student) {
students.push_back(student);
}
void StudentManagement::displayStudents() const {
std::cout << "List of students:\n";
for (const auto& student : students) {
std::cout << "Name: " << student.getName() << ", Age: " << student.getAge() << std::endl;
}
}
void StudentManagement::findStudentByName(const std::string& name) const {
bool found = false;
for (const auto& student : students) {
if (student.getName() == name) {
std::cout << "Found: Name: " << student.getName() << ", Age: " << student.getAge() << std::endl;
found = true;
break;
}
}
if (!found) {
std::cout << "Student with name '" << name << "' not found." << std::endl;
}
}
#include <iostream>
#include "student_management.h"
int main() {
StudentManagement sm;
int choice;
std::string name;
int age;
do {
std::cout << "Menu:\n";
std::cout << "1. Add Student\n";
std::cout << "2. Display Students\n";
std::cout << "3. Find Student by Name\n";
std::cout << "4. Exit\n";
std::cout << "Choose an option: ";
std::cin >> choice;
switch (choice) {
case 1:
std::cout << "Enter student name: ";
std::cin.ignore();
std::getline(std::cin, name);
std::cout << "Enter student age: ";
std::cin >> age;
sm.addStudent(Student(name, age));
break;
case 2:
sm.displayStudents();
break;
case 3:
std::cout << "Enter student name to search: ";
std::cin.ignore();
std::getline(std::cin, name);
sm.findStudentByName(name);
break;
case 4:
std::cout << "Exiting program." << std::endl;
break;
default:
std::cout << "Invalid choice! Please try again." << std::endl;
}
} while (choice != 4);
return 0;
}
Чтобы скомпилировать эту программу, выполните следующие команды в командной строке:
g++ -c student.cpp
g++ -c student_management.cpp
g++ -c main.cpp
g++ -o student_management_system main.o student.o student_management.o
Запустите программу с помощью команды:
./student_management_system
Этот пример демонстрирует базовые принципы модульного программирования на C++. Вы можете развивать его, добавляя больше функций, таких как удаление студентов или редактирование информации.
#ifndef BANK_H
#define BANK_H
#include <vector>
#include "account.h"
class Bank {
public:
void createAccount(const std::string& owner, double initial_balance);
void depositToAccount(const std::string& owner, double amount);
void withdrawFromAccount(const std::string& owner, double amount);
void displayAccounts() const;
private:
std::vector<Account> accounts;
};
#endif // BANK_H
#include "bank.h"
#include <iostream>
#include <algorithm>
void Bank::createAccount(const std::string& owner, double initial_balance) {
accounts.emplace_back(owner, initial_balance);
}
void Bank::depositToAccount(const std::string& owner, double amount) {
for (auto& account : accounts) {
if (account.getOwner() == owner) {
try {
account.deposit(amount);
std::cout << "Deposited " << amount << " to " << owner << "'s account." << std::endl;
return;
} catch (const std::invalid_argument& e) {
std::cerr << e.what() << std::endl;
return;
}
}
}
std::cerr << "Account not found." << std::endl;
}
void Bank::withdrawFromAccount(const std::string& owner, double amount) {
for (auto& account : accounts) {
if (account.getOwner() == owner) {
try {
account.withdraw(amount);
std::cout << "Withdrew " << amount << " from " << owner << "'s account." << std::endl;
return;
} catch (const std::runtime_error& e) {
std::cerr << e.what() << std::endl;
return;
}
}
}
std::cerr << "Account not found." << std::endl;
}
void Bank::displayAccounts() const {
std::cout << "Accounts:\n";
for (const auto& account : accounts) {
std::cout << "Owner: " << account.getOwner() << ", Balance: " << account.getBalance() << std::endl;
}
}
#include <iostream>
#include "bank.h"
int main() {
Bank bank;
int choice;
std::string owner;
double amount;
do {
std::cout << "Menu:\n";
std::cout << "1. Create Account\n";
std::cout << "2. Deposit\n";
std::cout << "3. Withdraw\n";
std::cout << "4. Display Accounts\n";
std::cout << "5. Exit\n";
std::cout << "Choose an option: ";
std::cin >> choice;
switch (choice) {
case 1:
std::cout << "Enter account owner: ";
std::cin.ignore();
std::getline(std::cin, owner);
std::cout << "Enter initial balance: ";
std::cin >> amount;
bank.createAccount(owner, amount);
break;
case 2:
std::cout << "Enter account owner: ";
std::cin.ignore();
std::getline(std::cin, owner);
std::cout << "Enter amount to deposit: ";
std::cin >> amount;
bank.depositToAccount(owner, amount);
break;
case 3:
std::cout << "Enter account owner: ";
std::cin.ignore();
std::getline(std::cin, owner);
std::cout << "Enter amount to withdraw: ";
std::cin >> amount;
bank.withdrawFromAccount(owner, amount);
break;
case 4:
bank.displayAccounts();
break;
case 5:
std::cout << "Exiting program." << std::endl;
break;
default:
std::cout << "Invalid choice! Please try again." << std::endl;
}
} while (choice != 5);
return 0;
}
Чтобы скомпилировать эту программу, выполните следующие команды в командной строке:
g++ -c account.cpp
g++ -c bank.cpp
g++ -c main.cpp
g++ -o bank_account_system main.o account.o bank.o
Запустите программу с помощью команды:
./bank_account_system
Меню: Программа предоставляет меню с возможностями:
Создание счета: Программа запрашивает имя владельца счета и начальный баланс.
Депозит: Программа запрашивает имя владельца счета и сумму для внесения на счет.
Снятие денег: Программа запрашивает имя владельца счета и сумму для снятия с счета.
Отображение счетов: Программа выводит на экран список всех счетов с именами владельцев и балансами.
Этот пример демонстрирует основы модульного программирования на C++ и может быть легко расширен дополнительными функциями, такими как удаление счетов, ведение истории транзакций и т.д.
Bank | 2 |
std::string | 2 |
std::vector | 1 |
std::cout | 8 |
std::cin | 4 |
std::endl | 2 |
this | 1 |
e | 1 |
id | 0 |
exception | 2 |
true/false | 0 |
Если вам нужно, чтобы я обосновал или объяснил какие-либо из приведенных выше чисел или уточнил какие-либо детали, дайте знать!