类与对象学习实例

这篇文章包含一系列编程任务,涉及创建和测试不同类。任务包括:实现复数类(加法和减法操作)、增强时间类(添加tick功能,递增秒数)、大整数类(存储40位数字,支持加减法及比较操作)、日期类(多种格式输出,构造函数初始化)以及储蓄账户类(计算利息和调整利率)。每个类都有相应的成员函数来执行特定操作,并在主程序中进行了测试。
摘要由CSDN通过智能技术生成

1.(Complex Class)

Create a class called Complex for performing arithmetic with complex numbers.
Write a program to test your class.
Complex numbers have the form
realPart + imaginaryPart * i  where i is - 1
Use double variables to represent the private data of the class. Provide a constructor that enables
an object of this class to be initialized when it is declared. The constructor should contain default
values in case no initializers are provided. Provide public member functions that perform the
following tasks:
(a) Adding two Complex numbers: The real parts ( 实部 ) are added together and the imaginary
parts ( 虚部 ) are added together.
(b) Subtracting two Complex numbers: The real part of the right operand is subtracted from the
real part of the left operand, and the imaginary part of the right operand is subtracted from the
imaginary part of the left operand.
(c) Printing Complex numbers in the form (a, b), where a is the real part and b is the imaginary
part.
注意点:
1.正确实现加减法:作为成员函数 有一个当前对象作为加数,只要一个参数即可
   正常实现加法,不改变两个加数,新建一个complex addResult 用来存储结果

#include<iostream>
using namespace std;
class Complex {
public:
	Complex(double real=0, double imagine=0) ://default
		realP(real), imagineP(imagine)
	{};
	Complex addComplex(Complex &addNum) {
		Complex addResult;
		addResult.realP = realP + addNum.realP;
		addResult.imagineP = imagineP + addNum.imagineP;
		//cout << "(" << realP<< "," << imagineP << ")+(" << addNum.realP << "," << addNum.imagineP << ")=(" << addResult.realP << "," << addResult.imagineP << ")" << endl;
		return  addResult;
	}
	void print()
	{
		cout << "(" << realP << " , " << imagineP << ")";
	}

	Complex subComplex(Complex &subNum) {
		Complex subResult;
		subResult.realP = realP - subNum.realP;
		subResult.imagineP = imagineP - subNum.imagineP;
		//cout << "(" << realP << "," << imagineP << ")-(" << subNum.realP << "," << subNum.imagineP << ")=(" << subResult.realP << "," << subResult.imagineP << ")" << endl;
		return subResult;
	}

	
private:
	double realP;
	double imagineP;

};

int main()
{
	Complex addnum1(1, 7);
	Complex addnum2(9, 2);
	Complex subnum1(10, 1);
	Complex subnum2(11,5);
	addnum1.addComplex(addnum2);
	addnum1.print(); cout << " + "; addnum2.print(); cout << " = "; addnum1.addComplex(addnum2).print(); cout << endl;
	subnum1.subComplex(subnum2);
	subnum1.print(); cout << " - "; subnum2.print(); cout << " = "; subnum1.subComplex(subnum2).print(); cout << endl;
	return 0;
}

2.Enhancing Class Time

Modify the Time class of Figs. 9.4-9.5 to include a tick member function
that increments the time stored in a Time object by one second . The Time object should always
remain in a consistent state. Write a program that tests the tick member function in a loop that
prints the time in standard format during each iteration of the loop to illustrate that the tick
member function works correctly. Be sure to test the following cases:
 a)Incrementing into the next minute.
 b)  Incrementing into the next hour.
 c)  Incrementing into the next day (i.e., 11:59:59 PM to 12:00:00 AM).
//Time.h
#pragma once
#ifndef TIME_H
#define TIME_H

// Time class definition
class Time
{
public:
	explicit Time(int = 0, int = 0, int = 0); // default constructor

	// set functions
	void setTime(int, int, int); // set hour, minute, second
	void setHour(int); // set hour (after validation)
	void setMinute(int); // set minute (after validation)
	void setSecond(int); // set second (after validation)

	// get functions
	unsigned int getHour() const; // return hour
	unsigned int getMinute() const; // return minute
	unsigned int getSecond() const; // return second
	void tick();

	void printUniversal() const; // output time in universal-time format
	void printStandard() const; // output time in standard-time format
private:
	unsigned int hour; // 0 - 23 (24-hour clock format)
	unsigned int minute; // 0 - 59
	unsigned int second; // 0 - 59
}; // end class Time

#endif

//time.cpp
#include <iostream>
#include <iomanip>
#include <stdexcept>
#include "Time.h" // include definition of class Time from Time.h
using namespace std;

// Time constructor initializes each data member 
Time::Time(int hour, int minute, int second)
{
	setTime(hour, minute, second); // validate and set time
} // end Time constructor

// set new Time value using universal time
void Time::setTime(int h, int m, int s)
{
	setHour(h); // set private field hour
	setMinute(m); // set private field minute
	setSecond(s); // set private field second
} // end function setTime

// set hour value
void Time::setHour(int h)
{
	if (h >= 0 && h < 24)
		hour = h;
	else
		throw invalid_argument("hour must be 0-23");
} // end function setHour

// set minute value
void Time::setMinute(int m)
{
	if (m >= 0 && m < 60)
		minute = m;
	else
		throw invalid_argument("minute must be 0-59");
} // end function setMinute

// set second value
void Time::setSecond(int s)
{
	if (s >= 0 && s < 60)
		second = s;
	else
		throw invalid_argument("second must be 0-59");
} // end function setSecond

// return hour value
unsigned int Time::getHour() const
{
	return hour;
} // end function getHour

// return minute value
unsigned int Time::getMinute() const
{
	return minute;
} // end function getMinute

// return second value
unsigned int Time::getSecond() const
{
	return second;
} // end function getSecond

// print Time in universal-time format (HH:MM:SS)
void Time::printUniversal() const
{
	cout << setfill('0') << setw(2) << getHour() << ":"
		<< setw(2) << getMinute() << ":" << setw(2) << getSecond();
} // end function printUniversal

// print Time in standard-time format (HH:MM:SS AM or PM)
void Time::printStandard() const
{
	cout << ((getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12)
		<< ":" << setfill('0') << setw(2) << getMinute()
		<< ":" << setw(2) << getSecond() << (hour < 12 ? " AM" : " PM")<<endl;
}
void Time::tick() //increment 1s
{
	if (second < 59)
		second++;
	else if (minute < 59)
	{
		minute++;second = 0;
	}
	else if (hour < 23)
	{
		hour++; minute = 0; second = 0;
	}
	else {
		hour = 0; minute = 0; second = 0;
	}

}

//源.cpp
#include <iostream>
#include <stdexcept>
#include "Time.h" // include definition of class Time from Time.h
using namespace std;

int main()
{
	Time time1(23, 59, 57);
	for (int i = 0; i < 15; i++)
	{
		time1.printStandard();
		time1.tick();
	}
} // end main

3.HugeInteger Class

Create a class HugeInteger that uses a 40-element array of digitsto store integers as large as 40 digits each. Provide member functions:

(a) Constructor, destructor
(b) input , output , add and substract
(c) For comparing HugeInteger objects, provide functions isEqualTo , isNotEqualTo ,
isGreaterThan , isLessThan , isGreaterThanOrEqualTo and isLessThanOrEqualToeach of these is a "predicate" function that simply returns   true if the relationship holds between the two HugeIntegers and returns false if the
relationship does not hold. Also, provide a predicate function isZero .
If you feel ambitious, provide member functions multiply , divide and modulus . 3
注:不考虑负数情况,即 hugeintA-hugeintB 确保 hugeintA 大于 hugeintB ;而
hugeintA+hugeintB ,不考虑溢出
难点:大整数作为数组存储 进行加减法 引入进位与借位 参与运算
//HugeInteger.h
#pragma once
class HugeInteger
{
public:
	HugeInteger(int = 0);
	HugeInteger(char*);
	~HugeInteger();

	void input(char*);//huge interger 字符串
	void output();

	HugeInteger add(int);//+小数
	HugeInteger add(const HugeInteger&);
	HugeInteger subtract(int);
	HugeInteger subtract(const HugeInteger&);

	bool isZero();
	bool isEqualTo(HugeInteger&);
	bool isNotEqualTo(HugeInteger&);
	bool isGreaterThan(HugeInteger &);
	bool isLessThan(HugeInteger &); // less than
	bool isGreaterThanOrEqualTo(HugeInteger &); // greater than // or equal to
	bool isLessThanOrEqualTo(HugeInteger &); // less than or equal

private:
	int integer[40];
};



//HugeInteger.cpp
#include"HugeInteger.h"
#include<iostream>
using namespace std;

HugeInteger::HugeInteger(int a) {
	for (int i = 0; i < 40; i++)
		integer[i] = a;
}

HugeInteger::HugeInteger(char*s)
{
	input(s);
}

HugeInteger::~HugeInteger() {};

void HugeInteger::input(char*s) //huge interger 字符串
{
	char *p = s;
	int len = 0;
	while (*p++ != '\0')
		len++;
	for (int i = 0; i < 39 - len + 1; i++)
		integer[i] = 0;
	for (int i = 39 - len + 1; i < 40; i++, s++)
	{
		integer[i] = *s - 48;//字符asc码转数字
	}
}

void HugeInteger::output()
{
	int j = 0;
	while (integer[j++] == 0);

	for (int i = j-1; i < 40; i++)
		cout << integer[i]; 
}

HugeInteger HugeInteger::add(int other)
{
	HugeInteger addResult;
	int carry = 0;//进位
	for (int i = 39; i >= 0; i--)
	{
		int a = other % 10;
		other = other / 10;
		addResult.integer[i] = (integer[i]+a+carry)%10;
		carry = (integer[i] + a + carry) / 10; //更新carry 
	}
	return addResult;
}
HugeInteger HugeInteger::add(const HugeInteger&other)
{
	HugeInteger result;
	int carry = 0;
	for (int i = 39; i >= 0; i--)
	{
		result.integer[i] = (integer[i] + other.integer[i] + carry) % 10;
		carry = (integer[i] + other.integer[i] + carry) / 10;
	}
	return result;
}
HugeInteger HugeInteger::subtract(int other)
{
	HugeInteger result;
	int borrow = 0;
	for (int i = 39; i >= 0; i--)
	{
		int a = other % 10;
		other = other / 10;
		int b = integer[i] - a - borrow;
		if (b >= 0)
		{
			result.integer[i] = b; borrow = 0;
		}
		else {
			result.integer[i] = b + 10;
			borrow = 1;
		}
	}
	return result;
}

HugeInteger HugeInteger::subtract(const HugeInteger&other)
{
	HugeInteger result;
	int borrow = 0;
	for (int i = 39; i >= 0; i--)
	{
		int a = integer[i] - other.integer[i] - borrow;
		if (a >= 0)
		{
			result.integer[i] = a;
			borrow = 0;
		}
		else
		{
			result.integer[i] = a + 10;
			borrow = 1;
		}
	}
	return result;
}
bool HugeInteger::isZero() {
	for (int i = 0; i < 40; i++)
	{
		if (integer[i] !=0)
			return false;
	}
	return true;
}
bool HugeInteger::isEqualTo(HugeInteger&other) {
	for (int i = 0; i < 40; i++)
	{
		if (integer[i] != other.integer[i])
			return false;
	}
	return true;
}
bool HugeInteger::isNotEqualTo(HugeInteger&other)
{
	for (int i = 0; i < 40; i++)
	{
		if (integer[i] != other.integer[i])
			return true;
	}
	return false;
}
bool HugeInteger::isGreaterThan(HugeInteger &other)
{
	for (int i = 0; i < 40; i++)
	{
		if (integer[i] > other.integer[i])
			return true;
		else if (integer[i] < other.integer[i])
			return false;
	}
	return false;
}

bool HugeInteger::isLessThan(HugeInteger &other)
{
	for (int i = 0; i < 40; i++)
	{
		if (integer[i] > other.integer[i])
			return false;
		else if (integer[i] < other.integer[i])
			return true;
	}
	return false;
}
bool HugeInteger::isGreaterThanOrEqualTo(HugeInteger &other) {
	for (int i = 0; i < 40; i++)
	{
		if (integer[i] > other.integer[i])
			return true;
		else if (integer[i] < other.integer[i])
			return false;
	}
	return true;
}
bool HugeInteger::isLessThanOrEqualTo(HugeInteger &other)
{
	for (int i = 0; i < 40; i++)
	{
		if (integer[i] > other.integer[i])
			return false;
		else if (integer[i] < other.integer[i])
			return true;
	}
	return true;
}

//源.cpp
#include<iostream>
#include"HugeInteger.h"
using namespace std;

int main()
{
	char s1[] = "7654321";
	char s2[] = "7891234";
	char s3[] = "5";
	int num1 = 5;
	int num2 = 0;
	HugeInteger int1(s1);
	HugeInteger int2(s2);
	HugeInteger int3(s3);

	int1.output(); cout << " + "; int2.output(); cout << " = "; int1.add(int2).output(); cout << endl;
	int2.output(); cout << " - " << num1; cout << " = "; int2.subtract(num1).output(); cout << endl;

	if (int1.isEqualTo(int1))
		int1.output(); cout << " is equal to "; int1.output(); cout << endl;
	if(int2.isNotEqualTo(int1))
		int2.output(); cout << " is not equal to "; int1.output(); cout << endl;
	if(int2.isGreaterThan(int1))
		int2.output(); cout << " is greater than "; int1.output(); cout << endl;

	if (int3.isLessThan(int2))
		int3.output(); cout << " is less than "; int2.output(); cout << endl;
	num1 <= 5 ? cout << "5 is less than or equal to 5"<< endl:cout << endl;
	num2 >= 0 ? cout << "0 is greater than or equal to 0" << endl : cout << endl;
	return 0;
}

4.Date class

 Modify class Date in Fig.9.17 to have the following capabilities:
 a. Output the date in multiple formats such as
      DDD YYYY
      MM/DD/YY
      June 14, 1992
 b. Use overloaded constructors to create Date objects initialized with dates of the formats in part (a).
 c. Create a Date constructor that reads the system date using the standard library functions of the <ctime> header and sets the Date members.
使用 <ctime> 头文件读取系统日期示例:
#include < ctime >
// default constructor that sets date using <ctime> functions
Date :: Date ()
{
// pointer of type struct tm which holds calendar time components
struct tm * ptr ;
time_t t = time ( 0 ); // determine current calendar time
// convert current calendar time pointed to by t into
// broken down time and assign it to ptr
ptr = localtime ( & t );
day = ptr -> tm_mday ; // broken down day of month
month = 1 + ptr -> tm_mon ; // broken down month since January
year = ptr -> tm_year + 1900; // broken down year since 1900
} // end Date constructor
以下代码使用类似函数localtime_s实现
//Date.h
#pragma once
#ifndef DATE_H
#define DATE_H
#include <string> 
using std::string;
class Date
{
public:
	Date(); // default constructor uses <ctime> functions to set date
	Date(int, int); // constructor using ddd yyyy format
	Date(int, int, int); // constructor using dd/mm/yy format
	Date(string, int, int); // constructor using Month dd, yyyy format

	void print() const; // print date in month/day/year format
	void printDDDYYYY() const; // print date in ddd yyyy format
	void printMMDDYY() const; // print date in mm/dd/yy format
	void printMonthDDYYYY() const; // print date in Month dd, yyyy format
	~Date(); // provided to confirm destruction order
private:
	int month; // 1-12 (January-December)
	int day; // 1-31 based on month
	int year; // any year
	const int  dayPerMon[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };

	// utility functions 
	int checkDay(int) const; // check if day is proper for month and year 
	bool isLeapYear() const; // indicates whether date is in a leap year
	int convertDDToDDD() const; // get 3-digit day based on month and day
	void setMMDDFromDDD(int); // set month and day based on 3-digit day
	string convertMMToMonth(int) const; // convert mm to month name
	void setMMFromMonth(string); // convert month name to mm 
	int convertYYYYToYY() const; // get 2-digit year based on 4-digit year
	void setYYYYFromYY(int); // set year based on 2-digit year
};
#endif

//Date.cpp
#include<iostream>
#include <ctime> 
#include<iomanip>
#include<string>
#include"Date.h"
using namespace std;

// default constructor that sets date using <ctime> functions
Date::Date()
{
	// pointer of type struct tm which holds calendar time components
	time_t t = time(0); // determine current calendar time 
	struct tm now_time;
	// convert current calendar time pointed to by t into
	// broken down time and assign it to ptr
	localtime_s(&now_time,&t);

	day = now_time.tm_mday; // broken down day of month
	month = 1 + now_time.tm_mon; // broken down month since January
	year = now_time.tm_year + 1900; // broken down year since 1900
} // end Date constructor

Date::Date(int dy, int yr) // constructor using ddd yyyy format
{
	setMMDDFromDDD(dy);
	year = yr;

}
Date::Date(int mn, int dy, int yr) // constructor using dd/mm/yy format
{
	day = dy;
	month = mn;
	setYYYYFromYY(yr);
}
Date::Date(string mn, int dy, int yr) // constructor using Month dd, yyyy format
{
	day = dy;
	year = yr;
	setMMFromMonth(mn);
}

void Date::print()const// print date in month/day/year format
{
	cout << month << "/" << day << "/" << year<<endl;
}

void Date::printDDDYYYY ()const// print date in ddd yyyy format
{
	cout << convertDDToDDD() << " " << year << endl;
}

void Date::printMMDDYY()const  // print date in mm/dd/yy format
{
	cout << setfill('0') << setw(2) << month << "/"
		<< setfill('0') << setw(2) << day << "/"
		<< setfill('0') << setw(2) << (year % 100) << endl;
}

void Date::printMonthDDYYYY()const // print date in Month dd, yyyy format
{
	cout << convertMMToMonth(month) << " " << day << " , " << year << endl;;
}


Date::~Date() 
{
	cout << "Date object destructor for date"; print();
	cout << endl;
} // provided to confirm destruction order

int Date::checkDay(int dy) const // check if day is proper for month and year 
{
    int monthPerYear[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };

	if (dy > 0 && day <= monthPerYear[month])
		return dy;
	if (month == 2 && dy == 29 && isLeapYear())
		return dy;

	throw invalid_argument("Invalid day for current month and year");
}

bool Date::isLeapYear() const // indicates whether date is in a leap year
{
	if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
		return true;
	else
		return false;
}
int Date::convertDDToDDD() const// get 3-digit day based on month and day
{
	int cnt = 0;
	int monthPerYear[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
	for (int i = 0; i <month; i++)
		cnt += monthPerYear[i];
	if ((month > 2 || (month == 2 && day == 29)) && isLeapYear())
		return cnt +day+ 1;
	return cnt+day;
}
void Date::setMMDDFromDDD(int dy) // set month and day based on 3-digit day
{
	int monthPerYear[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
	int mn = 1;
	while (dy != 0)
	{
		if (dy <= monthPerYear[mn])
		{
			day = dy; month = mn; dy = 0;
		}
		else {
			dy -= monthPerYear[mn];
			mn += 1;
		}
	}

}
string Date::convertMMToMonth(int mn) const // convert mm to month name
{
	const string monthNames[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
	return monthNames[month];
}
void Date::setMMFromMonth(string monthName) // convert month name to mm 
{
	const string monthNames[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
	int i = 1;
	for (; i <= 12; i++)
		if (monthNames[i] == monthName)
			month = i;
}
int Date::convertYYYYToYY() const // get 2-digit year based on 4-digit year
{
	return year % 100;
}
void Date::setYYYYFromYY(int yr)// set year based on 2-digit year
{
	year = 2000 + yr;
}

//源.cpp
#include<iostream>
#include"Date.h"
using namespace std;

int main()
{
	Date date1(256, 1999); // initialize using ddd yyyy format
	Date date2(3, 25, 04); // initialize using mm/dd/yy format
	Date date3("September", 1, 2000); // "month" dd, yyyy format
	Date date4; // initialize to current date with default constructor
	// print Date objects in default format
	date1.print();
	date2.print();
	date3.print();
	date4.print();
	cout << '\n';
	// print Date objects in 'ddd yyyy' format
	date1.printDDDYYYY();
	date2.printDDDYYYY();
	date3.printDDDYYYY();
	date4.printDDDYYYY();
	cout << '\n';
	// print Date objects in 'mm/dd/yy' format
	date1.printMMDDYY();
	date2.printMMDDYY();
	date3.printMMDDYY();
	date4.printMMDDYY();
	cout << '\n';
	// print Date objects in '"month" d, yyyy' format
	date1.printMonthDDYYYY();
	date2.printMonthDDYYYY();
	date3.printMonthDDYYYY();
	date4.printMonthDDYYYY();
	cout << endl;
	return 0;
} // end main

5. SavingAccount class

    Create a SavingsAccount class. Use a static data member annualInterestRate to store the annual interest rate for each of the 8 savers. Each member of the class contains a private data member   savingsBalance indicating the amount the saver currently has on deposit.
    Provide member function calculateMonthlyInterest that calculates the monthly interest by multiplying the balance by annualInterestRate divided by 12; this interest should be added to savingsBalance .
   Provide a static member function modifyInterestRate that sets the static annualInterestRate to a new value.
   Write a driver program to test class SavingsAccount . Instantiate two different objects of class SavingsAccount, saver1 and saver2 , with balances of $2000.00 and $3000.00, respectively. Set the annualInterestRate to 3 percent. Then calculate the monthly interest and print the new balances for each of the savers. Then set the  annualInterestRate to 4 percent, calculate the next month's interest and print the new balances for each of the savers.
细节错误:
getBalance()调用时忘记加()
#include<iostream>
#include<iomanip>
using namespace std;

class SavingAccount {
public:
	SavingAccount(double saving) 
	{
		savingsBalance = saving;
	}

	static double annualInterstRate;

	void calculateMonthlyInterest() {
		//cal
		monthlyInterst = savingsBalance * annualInterstRate / 12;
		//add
		savingsBalance += monthlyInterst;
	}

	static void modifyInterstRate(double ist) {
		annualInterstRate = ist;
	}
	double getSavingsBalance()
	{
		return savingsBalance;
	}

private:
	double savingsBalance;
	double monthlyInterst;
};

double SavingAccount::annualInterstRate = 0.03;//静态数据成员的初始化

void print(SavingAccount &saver1, SavingAccount &saver2)
{
	cout << "Saver1: $" <<fixed<<setprecision(2)<< saver1.getSavingsBalance() << "         " << "Saver2: $" << setprecision(2) << saver2.getSavingsBalance() << endl;
}
int main()
{
	SavingAccount saver1(2000.00);
	SavingAccount saver2(3000.00);

	cout << "Initial balnace:" << endl;
	print(saver1,saver2);

	saver1.calculateMonthlyInterest();//结算
	saver2.calculateMonthlyInterest();

    cout << "Balance after 1 month's interest applied at  .03: " << endl;
	print(saver1, saver2);

	saver1.modifyInterstRate(0.04);

	saver1.calculateMonthlyInterest();//结算
	saver2.calculateMonthlyInterest();

	cout << "Balance after 1 month's interest applied at  .04: " << endl;
	print(saver1, saver2);


	return 0;
}

6.IntegerSet class

Create class IntegerSet for which each object can hold integers
in the range 0 through 100. A set is represented internally as an array
of ones and zeros. Array element a[ i ] is 1 if integer i is in the set.
Array element a[ j ] is 0 if integer j is not in the set. The default
constructor initializes a set to the so-called "empty set," i.e., a set
whose array representation contains all zeros. 9
 a)  Provide member functions for the common set operations. For example,
provide a unionOfSets member function that creates a third set that
is the set-theoretic union of two existing sets (i.e., an element of
the third set's array is set to 1 if that element is 1 in either or
both of the existing sets, and an element of the third set's array
is set to 0 if that element is 0 in each of the existing sets).
 b)  Provide an intersectionOfSets member function which creates a third
set which is the set-theoretic intersection of two existing sets (i.e.,
an element of the third set's array is set to 0 if that element is
0 in either or both of the existing sets, and an element of the third
set's array is set to 1 if that element is 1 in each of the existing
sets).
 c)  Provide an insertElement member function that inserts a new integer
k into a set (by setting a[ k ] to 1). Provide a deleteElement member
function that deletes integer m (by setting a[ m ] to 0).
d)  Provide a printSet member function that prints a set as a list of
numbers separated by spaces. Print only those elements that are
present in the set (i.e., their position in the array has a value of
1). Print --- for an empty set.
Provide an isEqualTo member function that determines whether two sets
are equal.
Provide an additional constructor that receives an array of integers
and the size of that array and uses the array to initialize a set
object.
Now write a driver program to test your IntegerSet class. Instantiate
several IntegerSet objects. Test that all your member functions work
properly
注意点:重点防止数组下标越界!
#include<iostream>
using namespace std;

class IntegerSet {
public:
	//default
	IntegerSet() 
	{
		emptySet();
	}

	IntegerSet(int*arr,int size){
		emptySet();
		for (int i = 0; i < size; i++)
				intSet[arr[i]] =1;
	}

	IntegerSet unionOfIntegerSets(IntegerSet &otherSet)
	{
		IntegerSet unionSet;
		for (int i = 0; i < 101; i++)
		{
			if (intSet[i] + otherSet.intSet[i] == 0)
				unionSet.intSet[i] = 0;
			else
				unionSet.intSet[i] = 1;
		}
		return unionSet;
	}
	void emptySet()
	{
		for (int i = 0; i < 101; i++)
			intSet[i] = 0;
	}
	IntegerSet intersectionOfIntegerSets(IntegerSet &otherSet)
	{
		IntegerSet intersectionSet;
		for (int i = 0; i < 101; i++)
		{
			if (intSet[i] + otherSet.intSet[i] == 2)
				intersectionSet.intSet[i] = 1;
			else
				intersectionSet.intSet[i] = 0;
		}
		return intersectionSet;
	}
	void insertElement(int k) {
		if (k >= 0 && k < 101)
			intSet[k] = 1;
		else
			cout << "Invalid insert attempted!" << endl;
	}
	void deleteElement(int m) {
		intSet[m] = 0;
	}

	void setPrint() {
		cout << "(  ";
		for (int i = 0; i < 101; i++)
		{
			if (intSet[i] == 1)
				cout << i << "  ";
		}
		cout << "  )" << endl;
	}

	bool isEqualTo(IntegerSet &other)
	{
		for (int i = 0; i < 101; i++)
			if (intSet[i] != other.intSet[i])
				return 0;
		return 1;
	}

private:
	int intSet[101];//0-100 size101
};

void enterSet(int *input,int &size)
{
	int a = 0;
	size= 0;
	bool valid = 1;
	while (a != -1) {
	    valid = 1;
		cout << "Enter an element(-1 to end):";
		cin >> a;
		if (a>= 0 && a< 101||a==-1)
		input[size++] = a;
		else {
			valid = 0; cout << "Invalid Element." << endl;
		}
	}
	size--;
	if (valid)
		cout << "Entry complete." << endl;
}
int main()
{
	int input[5] = { 0 };
	int size = 5;

	enterSet(input, size);
    IntegerSet setA(input, size);
	setA.setPrint();

	enterSet(input, size);
	IntegerSet setB(input, size);
    setB.setPrint();

	cout << "Union of A and B is :" << endl;
	setA.unionOfIntegerSets(setB).setPrint();
	cout<< "Intersection of A and B is :" << endl;
	setA.intersectionOfIntegerSets(setB).setPrint();

	if (setA.isEqualTo(setB))
		cout << "Set A is equal to B" << endl;
	else
		cout << "Set A is not equal to B" << endl;

	cout << "Inseting 77 into set A..." << endl;
	setA.insertElement(77);
	cout << "setA is now :" << endl;
	setA.setPrint();

	cout << "Deleting 77 from setA..." << endl;
	setA.deleteElement(77);
	cout<< "setA is now :" << endl;
	setA.setPrint();


	return 0;
}

7.Time class

  It would be perfectly reasonable for the Time class of Figs.9.4-9.5 to
represent the time internally as the number of seconds since midnight
rather than the three integer values hour, minute and second.
  Clients could use the same public methods and get the same results. Modify the
Time class of Fig.9.4 to implement the time as the number of seconds since
midnight and show that there is no visible change in functionality to the
clients of the class. [Note: This exercise nicely demonstrates the virtues
of implementation hiding.]
注:将原来的 hour, minute 和 second 三个数据成员用 totalSeconds 一个替换。
类用户接口完全不变。
注意点:

事实上用户依旧是使用三个变量来设置时间,即使内部只有totalSeconds,

因此要convert (H,min,s) to totalSecons; 也需要为用户提供setHour()等函数

//Date.h
#pragma once
#ifndef TIME_H
#define TIME_H

// Time class definition
class Time
{
public:
	 // default constructor
	Time(int=0, int=0, int=0);

	// set functions
	void setTime(int, int, int); // set hour, minute, second
void setHour(int); // set hour (after validation)
	void setMinute(int); // set minute (after validation)
	void setSecond(int); // set second (after validation)

	// get functions
	unsigned int getHour() const; // return hour
	unsigned int getMinute() const; // return minute
	unsigned int getSecond() const; // return second

	void printUniversal() const; // output time in universal-time format
	void printStandard() const; // output time in standard-time format
private:
	int totalSeconds;
	//unsigned int hour; // 0 - 23 (24-hour clock format)
	//unsigned int minute; // 0 - 59
	//unsigned int second; // 0 - 59
}; // end class Time

#endif

//Date.cpp
#include<iostream>
#include<iomanip>
#include"Time.h"
using namespace std;


Time::Time(int h,int m,int s) {
	setTime(h, m, s);
}

void Time::setTime(int h, int m, int s) // set hour, minute, second
{
	totalSeconds = s + 60 * m + 3600 * h;
}
unsigned int Time::getHour() const // return hour
{
	return totalSeconds / 3600;   //***
}
unsigned int Time::getMinute() const// return minute
{
	return (totalSeconds % 3600)/60;
}
unsigned int Time::getSecond() const // return second
{
	return totalSeconds % 60;
}

void Time::setHour(int hour) {
	totalSeconds = hour * 3600 + getMinute() * 60 + getSecond();
}

void Time::setMinute(int minute) {
	totalSeconds = getHour() * 3600 + minute * 60 + getSecond();
}

void Time::setSecond(int second) {
	totalSeconds = getHour() * 3600 + getMinute() * 60 + second;
}

// print Time in universal-time format (HH:MM:SS)
void Time::printUniversal() const
{
	cout << setfill('0') << setw(2) << getHour() << ":"
		<< setw(2) << getMinute() << ":" << setw(2) << getSecond();
} // end function printUniversal

// print Time in standard-time format (HH:MM:SS AM or PM)
void Time::printStandard() const
{
	cout << ((getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12)
		<< ":" << setfill('0') << setw(2) << getMinute()
		<< ":" << setw(2) << getSecond() << (getHour() < 12 ? " AM" : " PM");
} // end function printStandard


//源.cpp
#include<iostream>
#include"Time.h"
using namespace std;

int main()
{
   Time t1; // all arguments defaulted
   Time t2( 2 ); // hour specified; minute and second defaulted
   Time t3( 21, 34 ); // hour and minute specified; second defaulted 
   Time t4( 12, 25, 42 ); // hour, minute and second specified

   cout << "Constructed with:\n\nt1: all arguments defaulted\n  ";
   t1.printUniversal(); // 00:00:00
   cout << "\n  ";
   t1.printStandard(); // 12:00:00 AM

   cout << "\n\nt2: hour specified; minute and second defaulted\n  ";
   t2.printUniversal(); // 02:00:00
   cout << "\n  ";
   t2.printStandard(); // 2:00:00 AM

   cout << "\n\nt3: hour and minute specified; second defaulted\n  ";
   t3.printUniversal(); // 21:34:00
   cout << "\n  ";
   t3.printStandard(); // 9:34:00 PM

   cout << "\n\nt4: hour, minute and second specified\n  ";
   t4.printUniversal(); // 12:25:42
   cout << "\n  ";
   t4.printStandard(); // 12:25:42 PM
	return 0;
}

8.17 (Rational Numbers) Create a class called Rational for performing arithmetic with fractions. Write a program to test your class. Use integer variables to represent the private instance variables of the class the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should store the fraction in reduced form. The fraction 2/4 is equivalent to 1/2 and would be stored in the object as 1 in the numerator and 2 in the denominator. Provide a no-argument constructor with default values in case no initializers are provided. Provide public methods that perform each of the following operations: a. Add two Rational numbers: The result of the addition should be stored in reduced form. b. Subtract two Rational numbers: The result of the subtraction should be stored in reduced form. c. Multiply two Rational numbers: The result of the multiplication should be stored in reduced form. d. Divide two Rational numbers: The result of the division should be stored in reduced form. e. Print Rational numbers in the form a/b, where a is the numerator and b is the denominator. f. Print Rational numbers in floating-point format. (Consider providing formatting capabilities that enable the user of the class to specify the number of digits of precision to the right of the decimal point.) – 提示: – 有理数是有分子、分母以形式a/b表示的数,其中a是分子,b是分母。例如,1/3,3/4,10/4。 – 有理数的分母不能为0,分子却可以为0。每个整数a等价于有理数a/1。有理数用于分数的精确计算中。例如1/3=0.0000…,它不能使用数据类型double或float的浮点格式精确表示出来,为了得到准确结果,必须使用有理数。 – Java提供了整数和浮点数的数据类型,但是没有提供有理数的类型。 – 由于有理数与整数、浮点数有许多共同特征,并且Number类是数字包装的根类,因此,把有理数类Rational定义为Number类的一个子类是比较合适的。由于有理数是可比较的,那么Rational类也应该实现Comparable接口。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值