0% нашли этот документ полезным (0 голосов)
20 просмотров10 страниц

Lab 6 C++

kki

Загружено:

Дин Туин
Авторское право
© © All Rights Reserved
Мы серьезно относимся к защите прав на контент. Если вы подозреваете, что это ваш контент, заявите об этом здесь.
Доступные форматы
Скачать в формате DOCX, PDF, TXT или читать онлайн в Scribd
0% нашли этот документ полезным (0 голосов)
20 просмотров10 страниц

Lab 6 C++

kki

Загружено:

Дин Туин
Авторское право
© © All Rights Reserved
Мы серьезно относимся к защите прав на контент. Если вы подозреваете, что это ваш контент, заявите об этом здесь.
Доступные форматы
Скачать в формате DOCX, PDF, TXT или читать онлайн в Scribd
Вы находитесь на странице: 1/ 10

LAB 7

Lab 6 Practice Exercises

Exercise 1
Create a class called Complex for performing arithmetic with complex numbers. Complex numbers
have the form real + i imag, where i = √-1.
Use floating point variables to represent the private data of the class.
Provide a constructor to initialize a complex number when it is declared.
The constructor should contain the default values in case no initializing values are provided.
Provide public member functions to perform the following operations:
• Addition of two Complex numbers
• Subtraction of two Complex numbers
• Multiplication of two Complex numbers
• Printing of a Complex number in a+ib format.
Write a driver program to test your class.

Создайте класс Complex для выполнения арифметических действий с комплексными числами.


Комплексные числа имеют вид real + i imag, где i = √-1.
Используйте переменные с плавающей запятой для представления личных данных класса.
Предоставьте конструктор для инициализации комплексного числа при его объявлении.
Конструктор должен содержать значения по умолчанию на случай, если инициализирующие
значения не указаны.
Предоставьте открытые функции-члены для выполнения следующих операций:
• Сложение двух комплексных чисел
• Вычитание двух комплексных чисел
• Умножение двух комплексных чисел
• Вывод комплексного числа в формате a+ib.
Напишите программу-драйвер для тестирования вашего класса.
LAB 7

#include <iostream>
using namespace std;

class Complex {
private:
float real;
float imag;

public:
Complex(float r = 0, float i = 0) : real(r), imag(i) {}

Complex add(const Complex& other) const {


return Complex(real + other.real, imag + other.imag);
}

Complex subtract(const Complex& other) const {


return Complex(real - other.real, imag - other.imag);
}

Complex multiply(const Complex& other) const {


return Complex(real * other.real - imag * other.imag,
real * other.imag + imag * other.real);
}

void print() const {


cout << real << " + i" << imag << endl;
}
};

int main() {
Complex num1(3, 2); // 3 + 2i
Complex num2(1, 7); // 1 + 7i

cout << "Number 1: ";


num1.print();

cout << "Number 2: ";


num2.print();

Complex sum = num1.add(num2);


cout << "Sum: ";
sum.print();

Complex difference = num1.subtract(num2);


cout << "Difference: ";
difference.print();

Complex product = num1.multiply(num2);


cout << "Product: ";
product.print();

return 0;
}
LAB 7

Exercise 2
Write a class to calculate the area and circumference of a circle.
Напишите класс для вычисления площади и длины окружности.

Class Circle

Private:
float radius;
Public:
2
ComputeArea(); //Area:Πr
ComputeCircumference(); //Circumfernce:2Πr

#include <iostream>
using namespace std;

class Circle {
private:
float radius;

public:
Circle(float r = 0) : radius(r) {}

float computeArea() const {


return 3.14159 * radius * radius;
}

float computeCircumference() const {


return 2 * 3.14159 * radius;
}

float getRadius() const {


return radius;
}
};

int main() {
Circle circle1(5);

cout << "Radius: " << circle1.getRadius() << endl;


cout << "Area: " << circle1.computeArea() << endl;
cout << "Circumference: " << circle1.computeCircumference() << endl;

return 0;
}
LAB 7
Exercise 3
Write a C++ class named date. Its member data should consist of three ints: month, day, and year. It
should also have two member functions: getdate(), which allows the user to enter a date in 12/31/02
format, and showdate(), which displays the date.

Напишите класс C++ с именем date. Его данные-члены должны состоять из трех целых
чисел: месяц, день и год. В нем также должны быть две функции-члена: getdate(), которая
позволяет пользователю вводить дату в формате 31.12.02, и showdate(), которая отображает
дату. год будет высокосным, если он либо кратен 4 и не кратен 100, либо кратен 400. Это
позволяет учитывать исключения для годов, кратных 100, но не кратных 400.

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

class Date {
private:
int month;
int day;
int year;

bool isLeapYear(int y) const {


return (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0));
}

bool isValidDate(int m, int d, int y) const {


if (m < 1 || m > 12) return false;

int daysInMonth;
switch (m) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
daysInMonth = 31;
break;
case 4: case 6: case 9: case 11:
daysInMonth = 30;
break;
case 2:
daysInMonth = isLeapYear(y) ? 29 : 28;
break;
default:
return false;
}

return (d >= 1 && d <= daysInMonth);


}

public:
void getDate() {
char slash;
bool valid = false;

do {
cout << "Enter date in MM/DD/YY format: ";
cin >> month >> slash >> day >> slash >> year;
LAB 7

if (year < 100) {


year += 2000;
}

if (isValidDate(month, day, year)) {


valid = true;
} else {
cout << "Invalid date. Please try again." << endl;
}
} while (!valid);
}

void showDate() const {


cout << "Date: " << setw(2) << setfill('0') << month << '/'
<< setw(2) << setfill('0') << day << '/'
<< setw(4) << setfill('0') << year << endl;
}
};

int main() {
Date date;

date.getDate();
date.showDate();

return 0;
}

Exercise 4
Create a class called ship that incorporates a ship’s number and location in longitudes and latitudes. A
member function of the ship class should get a position from the user and store it in the object; another
should report the serial number and position.
Write a main() program that creates three ships, asks the user to input the position of each, and then
displays each ship’s number and position.
Создайте класс с именем ship, который содержит номер судна и его местоположение в долготах
и широтах. Функция-член класса ship должна получать информацию о местоположении от
пользователя и сохранять ее в объекте; другая функция должна сообщать серийный номер и
местоположение.
Напишите программу main(), которая создает три корабля, просит пользователя ввести
местоположение каждого из них, а затем отображает номер и местоположение каждого корабля.

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

class Ship {
private:
int shipNumber;
LAB 7
float longitude;
float latitude;

public:

Ship(int number) : shipNumber(number), longitude(0.0), latitude(0.0) {}

void getPosition() {
cout << "Enter the longitude for ship " << shipNumber << ": ";
cin >> longitude;
cout << "Enter the latitude for ship " << shipNumber << ": ";
cin >> latitude;
}

void reportPosition() const {


cout << "Ship number: " << shipNumber << endl;
cout << "Position - Longitude: " << fixed << setprecision(2) << longitude
<< ", Latitude: " << latitude << endl;
}
};

int main() {

Ship ship1(1);
Ship ship2(2);
Ship ship3(3);

ship1.getPosition();
ship2.getPosition();
ship3.getPosition();

cout << "\nShip Positions:\n";


ship1.reportPosition();
ship2.reportPosition();
ship3.reportPosition();

return 0;
}

Exercise 5:
Create an employee class. The member data should comprise an int for storing the employee
number and a float for storing the employee’s compensation. Member functions should allow the
user to enter this data and display it. Write main() function that allows the user to enter data for
three employees and display it (Use Array of objects).

Создайте класс employee. Данные-члены должны содержать int для хранения номера сотрудника
и float для хранения вознаграждения сотрудника. Функции-члены должны позволять
пользователю вводить эти данные и отображать их. Напишите функцию main(), которая
позволяет пользователю вводить данные для трех сотрудников и отображать их (используйте
массив объектов).
LAB 7

#include <iostream>
using namespace std;

class Employee {
private:
int employeeNumber;
float compensation;

public:

void getData() {
cout << "Enter employee number: ";
cin >> employeeNumber;
cout << "Enter employee compensation: ";
cin >> compensation;
}

void displayData() const {


cout << "Employee Number: " << employeeNumber << endl;
cout << "Compensation: $" << compensation << endl;
}
};

int main() {
const int numEmployees = 3;
Employee employees[numEmployees];

for (int i = 0; i < numEmployees; i++) {


cout << "\nEnter details for employee " << (i + 1) << ":\n";
employees[i].getData();
}

cout << "\nEmployee Details:\n";


for (int i = 0; i < numEmployees; i++) {
cout << "\nEmployee " << (i + 1) << ":\n";
employees[i].displayData();
}

return 0;
}

Exercise 6:
Create a C++ class named Sphere, which has one data members, radius of the sphere. Write set()
and get() methods to store and return the radius of the Sphere class. It also has a function named
Area() which calculates the area of the Sphere. Input the radius from the user and calculate the
area of the Sphere.
Создайте класс C++ с именем Sphere, в котором есть один элемент данных - радиус сферы.
Напишите методы set() и get() для хранения и возврата значения радиуса класса Sphere. В нем
LAB 7
также есть функция Area(), которая вычисляет площадь сферы. Введите радиус от пользователя
и вычислите площадь сферы.

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

class Sphere {
private:
float radius;

public:
void set(float r) {
radius = r;
}

float area() const {


return 4 * M_PI * pow(radius, 2);
}
};

int main() {
Sphere sphere;
float radius;

cout << "Enter the radius of the sphere: ";


cin >> radius;

sphere.set(radius);

cout << "The surface area of the sphere is: " << sphere.area() << endl;

return 0;
}

Exercise 7:
Create a class named myString,which consists of one string data member and three functions.
Input the string from the user at run time then call the following functions on it.
• void CountConsonants( ) //displays the total number of consonants in the string
• void VowelCount( ) //displays the total vowels in the string
• void Palindrome( ) //displays if the string is a palindrome or not
Use pointer of object to call the member function of the class.
LAB 7
Создайте класс с именем myString, который состоит из одного элемента данных string и трех
функций. Введите строку от пользователя во время выполнения, а затем вызовите для нее
следующие функции.
• void CountConsonants( ) //отображает общее количество согласных в строке
• void VowelCount( ) //отображает общее количество гласных в строке
• void Palindrome( ) //отображает, является ли строка палиндромом или нет
Используйте указатель на объект для вызова функции-члена класса.

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

class myString {
private:
string str;

public:

void inputString() {
cout << "Enter a string: ";
getline(cin, str);
}

void CountConsonants() {
int count = 0;
for (char ch : str) {
ch = tolower(ch);
if (isalpha(ch) && !(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch
== 'u')) {
count++;
}
}
cout << "Total consonants: " << count << endl;
}

void VowelCount() {
int count = 0;
for (char ch : str) {
ch = tolower(ch);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
count++;
}
}
cout << "Total vowels: " << count << endl;
}

void Palindrome() {
string original = str;
LAB 7
original.erase(remove_if(original.begin(), original.end(), ::isspace),
original.end());
transform(original.begin(), original.end(), original.begin(), ::tolower);

string reversed = original;


reverse(reversed.begin(), reversed.end());

if (original == reversed) {
cout << "The string is a palindrome." << endl;
} else {
cout << "The string is not a palindrome." << endl;
}
}
};

int main() {
myString *s = new myString;

s->inputString();

s->CountConsonants();
s->VowelCount();
s->Palindrome();

delete s;
return 0;
}

Вам также может понравиться