lab 合集 one

DeeperLookClass

EX1:( Complex Class)

1. Description of the Problem
(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
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.

2. Sample Output
在这里插入图片描述
【我的代码】

#include<iostream>
using namespace std;
class Complex
{
public:
	Complex():realPart(0),imaginaryPart(0)
	{
	}
	void setComplexNumber(double a,double b)
	{
	realPart=a;imaginaryPart=b;
	}
	Complex adding(Complex b)
	{
		printing();
		cout<<"+";
		b.printing();
		cout<<"=";
		Complex temp;
		temp.realPart=realPart+b.realPart;
		temp.imaginaryPart=imaginaryPart+b.imaginaryPart;
		return temp;
	}
	Complex subtracting(Complex b)
	{
		printing();
		cout<<"-";
		b.printing();
		cout<<"=";
		Complex temp;
		temp.realPart=realPart-b.realPart;
		temp.imaginaryPart=imaginaryPart-b.imaginaryPart;
		return temp;
	}
	void printing()
	{
		cout<<"("<<realPart<<","<<imaginaryPart<<")";
	}
private:
	double realPart,imaginaryPart;
};

int main()
{
	Complex complexNumber[5];
	double a[4],b[4];
	for (int i=0;i<4;i++)
	{	cin>>a[i]>>b[i];
	complexNumber[i+1].setComplexNumber(a[i],b[i]);
	}
	complexNumber[1].adding(complexNumber[2]).printing();
	cout<<endl;
	complexNumber[3].subtracting(complexNumber[4]).printing();
	system("pause");
	return 0;
}

EX2: (Enhancing Class Time)

1. Description of the Problem
(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).
Note:
Then change the tick member function to a friend function of class Time, which will access the private data member of Time directly. You should get the same output as above.
friend void tick(Time &t);
// increment one second

2. Sample Output
在这里插入图片描述
【我的代码】

//Time.h
#ifndef TIME_H
#define TIME_H

class Time 
{
public:
	Time();
	void setTime(int,int,int);
	void printStandard() const;
	void tick(Time &);
private:
	unsigned int hour;
	unsigned int minute;
	unsigned int second;
};

#endif
//Time.cpp
#include<iostream>
#include<iomanip>
#include<stdexcept>
#include"Time.h"

using namespace std;

Time::Time()
	:hour(0),minute(0),second(0)
{
}

void Time::setTime(int h,int m,int s)
{
	if((h>=0&&h<=24)&&(m>=0&&m<60)&&(s>=0&&m<60))
	{
	hour=h;
	minute=m;
	second=s;
	}
	else 
		throw invalid_argument("hour,minute and/or second was out of range");
}

void Time::tick(Time &t)
{
	t.second++;
	if(t.second>59)
	{
		t.minute++;
		t.second-=60;
		if(t.minute>59)
		{	
			t.hour++;
			t.minute-=60;
		}
	}
}

void Time::printStandard()const
{
	cout<<((hour==0||hour==12)? 12:hour%12)<<":"
		<<setfill('0')<<setw(2)<<minute<<":"
		<<setw(2)<<second<<( hour<12 ? "AM":"PM")<<endl;
}
//TimeTest.cpp
#include<iostream>
#include<stdexcept>
#include"Time.h"
using namespace std;
int	main()
{
	Time t;
	t.setTime(11,59,57);
	for(int i=0;i<15;i++)
	{
	t.printStandard();
	t.tick(t);
	}
	system("pause");
	return 0;
}

EX3: (HugeInteger Class)

1. Description of the Problem
(HugeInteger Class) Create a class HugeInteger that uses a 40-element array of digits to store integers as large as 40 digits each. Provide member functions: (a) Constructor, destructor, (b) input, output, add and substract, © For comparing HugeInteger objects, provide functions isEqualTo, isNotEqualTo, isGreaterThan, isLessThan isGreaterThanOrEqualTo and isLessThanOrEqualToeach, each 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.
注:不考虑负数情况,即hugeintA-hugeintB确保hugeintA大于hugeintB;而hugeintA+hugeintB,确保不溢出

2. Sample Class Definition

#ifndef HUGEINTEGER_H 
#define HUGEINTEGER_H
class HugeInteger 
{ 
public: 
HugeInteger( int = 0 ); // conversion/default constructor 
HugeInteger( const char * ); // conversion constructor 
// addition operator; HugeInteger + HugeInteger 
HugeInteger add( const HugeInteger & ); 
// addition operator; HugeInteger + int 
HugeInteger add( int ); 
// addition operator; 
// HugeInteger + string that represents large integer value 
HugeInteger add( const char * ); 
// subtraction operator; HugeInteger - HugeInteger 
HugeInteger subtract( const HugeInteger & ); 
// subtraction operator; HugeInteger - int 
HugeInteger subtract( int ); 
// subtraction operator; 
// HugeInteger - string that represents large integer value 
HugeInteger subtract( const char * ); 
bool isEqualTo( HugeInteger & ); // is equal to 
bool isNotEqualTo( HugeInteger & ); // not equal to 
bool isGreaterThan(HugeInteger & ); // greater than 
bool isLessThan( HugeInteger & ); // less than 
bool isGreaterThanOrEqualTo( HugeInteger & ); // greater than 
// or equal to 
bool isLessThanOrEqualTo( HugeInteger & ); // less than or equal 
bool isZero(); // is zero 
void input( const char * ); // input 
void output(); // output 
private: 
int integer[ 40 ]; // 40 element array 
}; // end class HugeInteger 
#endif

3. Sample Output

在这里插入图片描述
【我的代码】

//hugeInteger.h
#ifndef HUGEINTEGER_H 
#define HUGEINTEGER_H

class HugeInteger 
{ 
public: 
	HugeInteger(int =0); 
	~HugeInteger();
	HugeInteger( const char * );
	HugeInteger add( const HugeInteger & ); 
	HugeInteger add( int ); 
	HugeInteger add( const char * ); 
	HugeInteger subtract( const HugeInteger & ); 
	HugeInteger subtract( int );
	HugeInteger subtract( const char * );
	bool isEqualTo( HugeInteger & ); 
	bool isNotEqualTo( HugeInteger & ); 
	bool isGreaterThan(HugeInteger & );
	bool isLessThan( HugeInteger & );
	bool isGreaterThanOrEqualTo( HugeInteger & );
	bool isLessThanOrEqualTo( HugeInteger & );
	bool isZero();
	void input( const char * );
	void output();
private: 
	int integer[40];
	int digit;//存储位数
};
#endif
//hugeInteger.cpp
#include<iostream>
#include<iomanip>
#include"hugeInteger.h"
using namespace std;
HugeInteger::HugeInteger(int x):digit(0)
{
	while(x!=0)
	{
	digit++;
	integer[40-digit]=x%10;
	x/=10;
	}
	for(int i=39-digit;i>=0;i--)
		integer[i]=0;
}

HugeInteger::~HugeInteger()
{
}

HugeInteger::HugeInteger(const char *a)
{
	input(a);
}


void HugeInteger::input(const char *a)
{
	digit=strlen(a);
	for(int i=39;i>=40-digit;i--)
		integer[i]=a[digit-(40-i)]-48;
	for(int i=39-digit;i>=0;i--)
		integer[i]=0;
}

HugeInteger HugeInteger::add(const HugeInteger &t)
{
	HugeInteger temp(0);
	int len=(digit>t.digit ? digit:t.digit);
	for(int i=39;i>=40-len;i--)
	{
		temp.integer[i]+=integer[i]+t.integer[i];
		if(temp.integer[i]>=10)
		{
		temp.integer[i]%=10;
		temp.integer[i-1]++;
		}
	}
	if(temp.integer[39-len]!=0)temp.digit=len+1;
	else temp.digit=len;
	return temp;
}

HugeInteger HugeInteger::add(int x)
{
	HugeInteger temp(x);
	return add(temp);
}

HugeInteger HugeInteger::add(const char *a)
{
	HugeInteger temp(a);
	return add(temp);
}

HugeInteger HugeInteger::subtract(const HugeInteger &t)
{
	HugeInteger temp(0);
	int len=(digit>t.digit ? digit:t.digit);
	for(int i=39;i>=40-len;i--)
	{
		temp.integer[i]+=integer[i]-t.integer[i];
		if(temp.integer[i]<0)
		{
		temp.integer[i]+=10;
		temp.integer[i-1]--;
		}
	}
	while(temp.integer[40-len]==0)
		len--;
	temp.digit=len;
	return temp;
}

HugeInteger HugeInteger::subtract(int x)
{
	HugeInteger temp(x);
	return subtract(temp);
}

HugeInteger HugeInteger::subtract(const char *a)
{
	HugeInteger temp(a);
	return subtract(temp);
}

bool HugeInteger::isEqualTo(HugeInteger &t)
{
	if(digit!=t.digit)return false;
	else for(int i=39;i>=40-digit;i--)
		if(integer[i]!=t.integer[i])return false;
	return true; 
}

bool HugeInteger::isGreaterThan(HugeInteger &t)
{
	if(digit>t.digit)return true;
	if(digit<t.digit)return false;
	else for(int i=40-digit;i<40;i++)
		{	if(integer[i]>t.integer[i])return true;
			if(integer[i]<t.integer[i])return false; }
	return false; 
}

bool HugeInteger::isLessThan(HugeInteger &t)
{
	if(isEqualTo(t)) return false;
	else return !(isGreaterThan(t));
}

bool HugeInteger::isGreaterThanOrEqualTo(HugeInteger &t)
{
	return !(isLessThan(t));
}

bool HugeInteger::isLessThanOrEqualTo(HugeInteger &t)
{
	return !(isGreaterThan(t));
}

bool HugeInteger::isNotEqualTo(HugeInteger &t)
{
	return !(isEqualTo(t));
}

bool HugeInteger::isZero()
{
	if(digit!=0)return false;
	else return true;
}

void HugeInteger::output()
{
	if(digit==0)cout<<0;
	else for(int i=40-digit;i<40;i++)
		cout<<integer[i];
}
//hugeIntegerTest.cpp
#include<iostream>
#include<iomanip>
#include"hugeInteger.h"
using namespace std;

int main()
{
	HugeInteger h1("7654321"),h2("7891234"),h3(5),h4(0);//n0,n1,n2,n3
	h1.output();cout<<" + ";h2.output();cout<<" = ";h1.add(h2).output();cout<<"\n\n";
	h2.output();cout<<" - ";h3.output();cout<<" = ";h2.subtract(5).output();cout<<"\n\n";
	h1.output();cout<<(h1.isEqualTo(h1)==true ? " is equal ":"is not equal to ");h1.output();cout<<"\n\n";
	h1.output();cout<<(h1.isEqualTo(h2)==true ? " is equal ":"is not equal to ");h2.output();cout<<"\n\n";
	h2.output();cout<<(h2.isGreaterThan(h1)==true ? " is greater than ":"is not greater than ");h1.output();cout<<"\n\n";
	h3.output();cout<<(h3.isLessThan(h2)==true ? " is less than ":" is greater than or equal to ");h2.output();cout<<"\n\n";
	h3.output();cout<<(h3.isLessThanOrEqualTo(h3)==true ? " is less than or equal to ":" is greater than ");h3.output();cout<<"\n\n";
	h4.output();cout<<(h4.isLessThanOrEqualTo(h4)==true ? " is greater than or equal to ":" is less than ");h4.output();cout<<"\n\n";
	cout<<"n3 "<<(h4.isZero()==true? "contains ":"doesn't contain ")<<"value 0"<<endl;
	system("pause");
	return 0;
}

本想着给了类定义样例很友善,没想到反而限制了我的思路,oop真是不简单啊,但我还是会爬的!

EX4: Integer Set

1. Description of the Problem

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.

Provide member functions for the common set operations.
For example, a unionOfSets member function(already provided) creates a third set that is the set-theoretic union of two existing sets (i.e., an element of thethird array’s is set to 1 if that element is 1 in either or both of the existing sets, and an element of the third set’sarray is set to 0 if that element is 0 in each of the existing sets).

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).

An insertElement member function (already provided) 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).

A printSet member function (already provided) prints a set as a list of numbers separated by spaces. Print only those elements which 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.

2. Sample Output
在这里插入图片描述
3. Problem-Solving Tips
1) Member function intersectionOfSets must return an IntegerSet object. The object that invokes this function and the argument passed to the member function should not be modified by the operation .intersectionOfSets should iterate over all integers an IntegerSet could contain (1–100) and add those integers that both IntegerSets contain to a temporary IntegerSet that will be returned.
2) Member function deleteElement should first verify that its argument is valid by calling utility function validEntry. If so, the corresponding element in the set array should be set to 0; otherwise, display an error message.
3) Member function isEqualTo should iterate over all integers an IntegerSet could contain and (1–100).If any integer is found that is in one set but not the other, return false; otherwise return true.

在这里插入图片描述
在这里插入图片描述
【我的代码】

//IntegerSet.h
#ifndef INTEGERSET_H
#define INTEGERSET_H
class IntegerSet
{
public:
	IntegerSet();
	IntegerSet(int [],const int);
	void inputSet();
	IntegerSet unionOfSets(IntegerSet &);
	IntegerSet intersectionOfSets(IntegerSet &);
	void insertElement(int);
	bool isEqualTo(IntegerSet &);
	void deleteElement(int);
	void printSet();
private:
	int a[101];
	bool validEntry(int);
};
#endif
//IntegerSet.cpp
#include<iostream>
#include<iomanip>
#include "IntegerSet.h"
using namespace std;

IntegerSet::IntegerSet()
{
	for(int i=0;i<101;i++)
	a[i]=0;
}

IntegerSet::IntegerSet(int intArray[], const int size)
{
	for(int i=0;i<101;i++)
		a[i]=0;
	for(int i=0;i<size;i++)
		if(validEntry(intArray[i])) a[intArray[i]]=1;
		else cout<<"Invalid insert attempted!"<<endl;
}

void IntegerSet::inputSet()
{
	int x;
	do
	{
	cout<<"Enter an element (-1 to end): ";
	cin>>x;
	if(validEntry(x))
		a[x]=1;
	else 
	{
		if(x!=-1) cout<<"Invalid insert attempted!"<<endl;
	}
	}while(x!=-1);
	cout<<"Entry complete"<<endl;
}
IntegerSet IntegerSet::unionOfSets(IntegerSet &b)
{
	cout<<"\nUnion of A and B is: "<<endl;
	IntegerSet c;
	for(int i=0;i<101;i++)
		if(a[i]==1||b.a[i]==1)
			c.a[i]=1;
	return c;
}
IntegerSet IntegerSet::intersectionOfSets(IntegerSet &b)
{
	cout<<"Intersection of A and B is: "<<endl;
	IntegerSet c;
	for(int i=0;i<101;i++)
		if(a[i]==1&&b.a[i]==1)
			c.a[i]=1;
	return c;
}

void IntegerSet::insertElement(int x)
{
	if(validEntry(x))
		a[x]=1;
	else cout<<"Invalid insert attempted!"<<endl;
}

void IntegerSet::deleteElement(int x)
{
	if(validEntry(x))
		a[x]=0;
	else cout<<"Invalid insert attempted!"<<endl;
}

bool IntegerSet::isEqualTo(IntegerSet &b)
{
	for(int i=0;i<101;i++)
		if(a[i]!=b.a[i])return false;
	return true;
}

bool IntegerSet::validEntry(int x)
{
	if(x>=0&&x<101)
		return true;
	else 
		return false;
}

void IntegerSet::printSet()
{
	cout<<"{";
	for(int i=0;i<101;i++)
		if(a[i]!=0)cout<<setw(4)<<i;
	cout<<setw(4)<<"}"<<endl;
}
//Integer Set.cpp
#include<iostream>
#include "IntegerSet.h"
using namespace std;
int main()
{
	IntegerSet a;
	IntegerSet b;
	IntegerSet c;
	IntegerSet d;
	cout<<"Enter set A:\n";
	a.inputSet();
	cout<<"\nEnter set B:\n";
	b.inputSet();
	c=a.unionOfSets(b);
	c.printSet();
	d=a.intersectionOfSets(b);
	d.printSet();
	if(a.isEqualTo(b))
		cout<<"Set A is equal to set B\n";
	else 
		cout<<"Set A is not equal to set B\n";
	cout<<"\nIntersecting 77 into set A...\n";
	a.insertElement(77);
	cout<<"Set A is now:\n";
	a.printSet();
	cout<<"\nDeleting 77 from set A...\n";
	a.deleteElement(77);
	cout<<"Set A is now:\n";
	a.printSet();
	const int arraySize=10;
	int intArray[arraySize]={25,67,2,9,99,105,45,-5,100,1};
	IntegerSet e(intArray,arraySize);
	cout<<"\nSet e is:\n";
	e.printSet();
	cout<<endl;
	system("pause");
	return 0;
}

安,wish a good dream!

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值