1.
【描述】
声明并实现一个Point类,表示直角坐标系中的一个点。Point类包括:
double类型的私有数据成员x和y,表示坐标。
无参(默认)构造函数,将坐标设置为原点。
有参构造函数,将坐标设置为给定的参数。
访问器函数getX和getY,分别用于访问点的x坐标和y坐标。
【输入】
0,0 4,5
【输出】
(0,0) (4,5)
#include <iostream>
using namespace std;
// 请在此处编写Point类
class Point{
private:
double x;
double y;
public:
Point() : x(0),y(0) {}
Point(double xVal,double yVal) : x(xVal),y(yVal) {}
double getX() const{
return x;
}
double getY() const{
return y;
}
};
int main() {
double x, y;
char ignore;
cin >> x >> ignore >> y;
Point p1(x, y);
cin >> x >> ignore >> y;
Point p2(x, y);
cout << "(" << p1.getX() << "," << p1.getY() << ")" << endl;
cout << "(" << p2.getX() << "," << p2.getY() << ")" << endl;
return 0;
}
2.
【描述】
声明并实现一个Rectangle类,表示矩形。Rectangle类包括:
double类型的私有数据成员width和height,表示矩形的宽和高。
带默认参数的构造函数,将矩形的宽和高设置为给定的参数。宽和高的默认参数值为1。
更改器函数setWidth和setHeight,分别用于修改矩形的宽和高。
访问器函数getWidth和getHeight,分别用于访问矩形的宽和高。
成员函数computeArea,返回矩形的面积。
成员函数computePerimeter,返回矩形的周长。
【输入】
5 40 10 3.5
【输出】
200 90 35 27
#include <iostream>
using namespace std;
// 请在此处编写Rectangle类
class Rectangle{
private:
double width;
double height;
public:
Rectangle(double w = 1,double h = 1) : width(w),height(h) {}
void setWidth(double w){
width = w;
}
void setHeight(double h){
height = h;
}
double getWidth() const{
return width;
}
double getHeight() const{
return height;
}
double computeArea() const{
return width * height;
}
double computePerimeter() const{
return 2 * (width + height);
}
};
int main() {
double width, height;
cin >> width >> height;
Rectangle rect1;
rect1.setWidth(width);
rect1.setHeight(height);
cin >> width >> height;
Rectangle rect2(width, height);
cout << rect1.computeArea() << " " << rect1.computePerimeter() << endl;
cout << rect2.computeArea() << " " << rect2.computePerimeter() << endl;
return 0;
}
3.
【描述】
声明并实现一个Cylinder类,表示圆柱体。Cylinder类包括:
double类型的私有数据成员radius和height,分别表示圆柱体底半径和高。
带默认参数的构造函数,将圆柱体底半径和高设置为给定的参数。半径和高的默认参数值为1。
访问器函数,分别用于访问圆柱体底半径和高。
成员函数computeVolume,返回圆柱体体积。
成员函数computeSurfaceArea,返回圆柱体表面积。
假设PI为3.14159。
【输入】
输入圆柱体的底半径和高。
【输出】
输出圆柱体的体积和表面积。
【输入示例】
4 8
【输出示例】
402.124 301.593
#include <iostream>
using namespace std;
const double PI = 3.14159;
// 请在此处编写Cylinder类
class Cylinder{
private:
double radius;
double height;
public:
Cylinder(double r = 1,double h =1 ) : radius(r),height(h) {}
double getRadius() const{
return radius;
}
double getHeight() const{
return height;
}
double computeVolume() const{
return PI * radius * radius * height;
}
double computeSurfaceArea() const{
return 2 * PI * radius * (radius + height);
}
};
int main() {
double radius, height;
cin >> radius >> height;
Cylinder cylinder(radius, height);
cout << cylinder.computeVolume() << endl;
cout << cylinder.computeSurfaceArea() << endl;
return 0;
}
4.
【描述】
声明并实现一个Account类,表示银行账户。Account类包括:
string类型的私有数据成员id,表示账号;string类型的私有数据成员name,表示客户名;double类型的私有数据成员balance,表示账户余额;double类型的私有数据成员annualInterestRate,表示年利率。
有参构造函数,将账号、客户名、账户余额、年利率设置为给定的参数。
更改器函数setId、setName、setBalance和setAnnualInterestRate,分别用于修改账号、客户名、账户余额、年利率。
访问器函数getId、getName、getBalance和getAnnualInterestRate,分别用于访问账号、客户名、账户余额、年利率。
成员函数withdraw,从账户中取款。
成员函数deposit,往账户中存款。
成员函数computeMonthlyInterestRate,返回月利率。
成员函数print,输出账户信息。
【输入】
输入账号、客户名、账户余额和年利率。
【输出】
输出账号、客户名、账户余额和月利率。
【输入示例】
112233 ZhangSan 20000 4.5
【输出示例】
112233 ZhangSan 20500 0.375%
#include <iostream>
#include <string>
using namespace std;
#include<cmath>
#include<string>
#include<cstring>
#include<sstream>
#include<vector>
#include<array>
#include<algorithm>
#include<iomanip>
#include<map>
#include<cstdlib>
class Account{
private:
string id;
string name;
double balance;
double annualInterestRate;
public:
Account(string id,string name,double balance,double annualInterestRate) : id(id),name(name),balance(balance),annualInterestRate(annualInterestRate) {}
void setId(const string& id){
this->id = id;
}
void setName(const string& name){
this->name = name;
}
void setBalance(double balance){
this->balance = balance;
}
void setAnnualInterestRate(double annualInterestRate){
this->annualInterestRate = annualInterestRate;
}
string getId() const{
return id;
}
string getName() const{
return name;
}
double getBalance() const{
return balance;
}
double getAnnualInterestRate() const{
return annualInterestRate;
}
void withdraw(double amount){
if(amount <= balance){
balance -= amount;
//cout << "Withdrawal of " << amount << "successful.\n";
}else{
//cout << "Insufficient balance for withdrawal of " << amount << ".\n";
}
}
void deposit(double amount){
balance += amount;
// cout << "Deposit of " << amount << "successful.\n";
}
double computeMonthlyInterestRate() const{
return annualInterestRate / 12;
}
void print() const{
cout << getId() << endl;
cout << getName() << endl;
cout << getBalance() << endl;
cout << fixed << setprecision(3) << computeMonthlyInterestRate() << "%" << endl;
}
};
int main() {
string id;
string name;
double balance;
double annualInterestRate;
cin >> id >> name >> balance >> annualInterestRate;
Account account(id, name, balance, annualInterestRate);
account.withdraw(2500);
account.deposit(3000);
account.print();
return 0;
}
5.
【描述】
声明并实现一个Loan类,表示贷款。Loan类包括:
double类型的私有数据成员loanAmount,表示贷款额。double类型的私有数据成员annualInterestRate,表示贷款年利率。int类型的私有数据成员numberOfYears,表示贷款年限。
有参构造函数,将贷款额、贷款年利率、贷款年限设置为给定的参数。
更改器函数setLoanAmount、setAnnualInterestRate和setNumberOfYears,分别用于修改贷款额、贷款年利率、贷款年限。
访问器函数getLoanAmount、getAnnualInterestRate和getNumberOfYears,分别用于访问贷款额、贷款年利率、贷款年限。
成员函数getMonthlyPayment,返回月还款额。
成员函数getTotalPayment,返回总还款额。
【输入】
输入贷款额、贷款年利率、贷款年限。
【输出】
月还款额和总还款额。
【输入示例】
60000 6.25 15
【输出示例】
514.454 92601.7
#include <iostream>
#include <cmath>
using namespace std;
// 请在此处编写Loan类
class Loan{
private:
double loanAmount;
double annualInterestRate;
int numberOfYears;
public:
Loan(double amount,double interestRate,int years){
loanAmount = amount;
annualInterestRate = interestRate;
numberOfYears = years;
}
void setLoanAmount(double amount){
loanAmount = amount;
}
void setAnnualInterestRate(double interestRate){
annualInterestRate = interestRate;
}
void setNumberOfYears(int years){
numberOfYears = years;
}
double getLoanAmount() const{
return loanAmount;
}
double getAnnualInterestRate() const{
return annualInterestRate;
}
double getNumberOfYears() const{
return numberOfYears;
}
double getMonthlyPayment() const{
double monthlyInterestRate = annualInterestRate / 100 / 12;
int numberOfPayments = numberOfYears * 12;
return (loanAmount * monthlyInterestRate) / (1 - pow(1+monthlyInterestRate,-numberOfPayments));
}
double getTotalPayment() const{
return getMonthlyPayment() * numberOfYears * 12;
}
};
int main() {
double loanAmount, annualInterestRate;
int numberOfYears;
cin >> loanAmount;
cin >> annualInterestRate;
cin >> numberOfYears;
Loan loan(loanAmount, annualInterestRate, numberOfYears);
cout << loan.getMonthlyPayment() << endl;
cout << loan.getTotalPayment() << endl;
return 0;
}
6.
【描述】
声明并实现一个Time类,表示时间。Time类包括:
int类型的私有数据成员hour、minute、second,表示时、分、秒。
带默认参数的构造函数,将时、分、秒设置为给定的参数。时、分、秒的默认参数值为0。需要检查时、分、秒的有效性。若超出允许范围,则抛出invalid_argument标准异常。
更改器函数setHour、setMinute和setSecond,分别用于修改时、分、秒。每个更改器函数都要检查对应的时、分、秒的有效性。若超出允许范围,则抛出invalid_argument标准异常。
访问器函数getHour、getMinute和getSecond,分别用于访问时、分、秒。
成员函数setTime,用于同时修改时、分、秒。需要检查时、分、秒的有效性。若超出允许范围,则抛出invalid_argument标准异常。
成员函数printTime24,以24小时制格式输出时间,格式为时:分:秒。
成员函数printTime12,以12小时制格式输出时间,格式为上午或下午时:分:秒。
成员函数tick,将时间递增1秒。要考虑增加1秒后,时间增加到下一分钟、下一小时、下一天的情况。
【输入】
没有输入。
【输出】
00:00:00 AM12:00:00 02:00:00 AM2:00:00 21:34:00 PM9:34:00 12:25:42 PM12:25:42 Invalid argument! 00:00:00 AM12:00:00
#include <iostream>
#include <iomanip>
#include <stdexcept>
using namespace std;
// 请在此处编写Time类
class Time {
private:
int hour;
int minute;
int second;
void validateTime(int h, int m, int s) {
if (h < 0 || h > 23 || m < 0 || m > 59 || s < 0 || s > 59) {
throw invalid_argument("Invalid argument!");
}
}
public:
Time(int h = 0, int m = 0, int s = 0) {
validateTime(h, m, s);
hour = h;
minute = m;
second = s;
}
void setHour(int h) {
validateTime(h, minute, second);
hour = h;
}
void setMinute(int m) {
validateTime(hour, m, second);
minute = m;
}
void setSecond(int s) {
validateTime(hour, minute, s);
second = s;
}
int getHour() const {
return hour;
}
int getMinute() const {
return minute;
}
int getSecond() const {
return second;
}
void setTime(int h, int m, int s) {
validateTime(h, m, s);
hour = h;
minute = m;
second = s;
}
void printTime24() const {
cout << setfill('0') << setw(2) << hour << ":"
<< setw(2) << minute << ":"
<< setw(2) << second << endl;
}
void printTime12() const {
string period = (hour < 12) ? "AM" : "PM";
int displayHour = hour % 12;
if (displayHour == 0) {
displayHour = 12;
}
cout << period << displayHour << ":"
<< setfill('0') << setw(2) << minute << ":"
<< setw(2) << second << endl;
}
void tick() {
second++;
if (second > 59) {
second = 0;
minute++;
}
if (minute > 59) {
minute = 0;
hour++;
}
if (hour > 23) {
hour = 0;
}
}
};
int main() {
Time t1;
t1.printTime24();
t1.printTime12();
Time t2(2);
t2.printTime24();
t2.printTime12();
Time t3(21, 34);
t3.printTime24();
t3.printTime12();
Time t4(12, 25, 42);
t4.printTime24();
t4.printTime12();
try {
Time t5(23, 59, 99);
}
catch(invalid_argument &ex) {
cout << ex.what() << endl;
}
Time t6(23, 59, 59);
t6.tick();
t6.printTime24();
t6.printTime12();
return 0;
}
7.
【描述】
自定义异常类NegativeNumberException,表示对负数执行操作时出现的异常,如计算负数的平方根。该类有一个string类型的私有数据成员message,用来存放异常信息;一个无参(默认)构造函数和一个有参构造函数,用来设置异常信息;成员函数what,用来显示异常信息。在main函数中,让用户输入某个数,并调用squareRoot函数,计算该数的平方根。如果输入的是负数,squareRoot函数将抛出NegativeNumberException异常,否则返回该数的平方根。
【输入】
输入一个数。
【输出】
输出该数的平方根或者输出错误信息“Invalid argument!”。
【输入示例】
-8
【输出示例】
Invalid argument
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
// 请在此处分别编写NegativeNumberException类和squareRoot函数
class NegativeNumberException {
private:
string message;
public:
NegativeNumberException() : message("Invalid argument!") {}
NegativeNumberException(const string& msg) : message(msg) {}
const string& what() const {
return message;
}
};
double squareRoot(double value) {
if (value < 0) {
throw NegativeNumberException();
}
return sqrt(value);
}
int main() {
double value;
cin >> value;
try {
cout << squareRoot(value) << endl;
}
catch(NegativeNumberException &ex) {
cout << ex.what() << endl;
}
return 0;
}
8.
【描述】
自定义异常类TriangleException。该类有一个string类型的私有数据成员message,用来存放异常信息;一个无参(默认)构造函数(默认值为“Exception”)和一个有参构造函数,用来设置异常信息;成员函数what,用来显示异常信息。
声明并实现一个Triangle类,表示三角形。Triangle类包括:
double类型的私有数据成员side1、side2、side3,表示三角形三条边。
私有成员函数isValid,判断三条边能否构成三角形。如果能构成三角形,返回true,否则返回false。
私有成员函数check,判断边是否大于0。如果边大于0,返回true,否则返回false。
带默认参数的构造函数,将三角形三条边设置为给定的参数。三条边的默认参数值为1。需要调用check函数检查边是否大于0,如果边小于等于0,则抛出TriangleException异常;以及调用isValid函数判断更改边后能否构成三角形,如果不能构成三角形,则抛出TriangleException异常。
更改器函数setSide1、setSide2和setSide3,分别用于修改三角形三条边。和构造函数一样,每个更改器函数需要调用check函数和isValid函数检查边的有效性。
访问器函数getSide1、getSide2和getSide3,分别用于访问三角形三条边。
成员函数computeArea,返回三角形面积。
成员函数computePerimeter,返回三角形周长。
【输入】
输入三角形的三条边,边长以空格间隔。
【输出】
若三条边有负数,输出“Negative side”。
若三条边能构成三角形,输出三角形面积和周长,以空格间隔。
若不能构成三角形,输出“Don't make a triangle”。
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
// 请在此处分别编写TriangleException类和Triangle类
class TriangleException {
private:
string message;
public:
TriangleException() : message("Exception") {}
TriangleException(const string& msg) : message(msg) {}
const string& what() const {
return message;
}
};
class Triangle {
private:
double side1, side2, side3;
bool check(double side) {
return side > 0;
}
bool isValid() {
return (side1 + side2 > side3) &&
(side1 + side3 > side2) &&
(side2 + side3 > side1);
}
public:
Triangle(double s1 = 1, double s2 = 1, double s3 = 1) {
if (!check(s1) || !check(s2) || !check(s3)) {
throw TriangleException("Negative side");
}
side1 = s1;
side2 = s2;
side3 = s3;
if (!isValid()) {
throw TriangleException("Don't make a triangle");
}
}
void setSide1(double s1) {
if (!check(s1)) {
throw TriangleException("Negative side");
}
side1 = s1;
if (!isValid()) {
throw TriangleException("Don't make a triangle");
}
}
void setSide2(double s2) {
if (!check(s2)) {
throw TriangleException("Negative side");
}
side2 = s2;
if (!isValid()) {
throw TriangleException("Don't make a triangle");
}
}
void setSide3(double s3) {
if (!check(s3)) {
throw TriangleException("Negative side");
}
side3 = s3;
if (!isValid()) {
throw TriangleException("Don't make a triangle");
}
}
double getSide1() const { return side1; }
double getSide2() const { return side2; }
double getSide3() const { return side3; }
double computeArea() const {
double s = computePerimeter() / 2;
return sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
double computePerimeter() const {
return side1 + side2 + side3;
}
};
int main() {
double side1, side2, side3;
try {
cin >> side1 >> side2 >> side3;
Triangle triangle(side1, side2, side3);
cout << triangle.computePerimeter() << " "
<< triangle.computeArea() << endl;
}
catch(TriangleException &ex) {
cout << ex.what() << endl;
}
return 0;
}
9.
【描述】
有理数是由分子和分母组成的a/b形式的数,a是分子,b是分母。例如,1/3、3/4和10/4等都是有理数。有理数不能以0为分母,但可以以0为分子。整数a等价于有理数a/1。
有理数用于包含分数的精确运算。例如,1/3=0.333333……,这个数是不能用浮点数精确表示,为了得到精确的结果,必须使用有理数。
一个有理数可能有很多与其值相等的其他有理数,例如,1/3=2/6=3/9=4/12。为简单起见,用1/3表示所有值等于1/3的有理数。因此,需要对有理数进行优化,使分子和分母之间没有公约数(1除外)。求分子和分母绝对值的最大公约数,然后将分子和分母都除以此最大公约数,得到有理数的优化表示形式。
声明并实现一个Rational类,表示有理数。Rational类包括:
int类型的私有数据成员numerator、denominator,表示分子、分母。
私有成员函数gcd,用于求分子、分母的最大公约数。
带默认参数的构造函数,将分子、分母设置为给定的参数。分子、分母的默认参数值分别为0、1。
访问器函数getNumerator、getDenominator,分别用于访问分子、分母。
成员函数add、subtract、multiply、divide,实现有理数的+、-、×和÷运算。
成员函数equals,判断一个有理数与另一个有理数是否相等。如果相等,返回true,否则返回false。
成员函数doubleValue,将有理数转换为浮点数。
成员函数print,输出一个有理数。若分母为0,则输出“Inf”。
【输入】
4/2 2/3
【输出】
2 2/3 8/3 4/3 4/3 3 a!=b 0.666667
#include <iostream>
using namespace std;
#include<iomanip>
class Rational {
private:
int numerator;
int denominator;
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return abs(a);
}
void reduce() {
if (denominator < 0) {
numerator = -numerator;
denominator = -denominator;
}
int gcdVal = gcd(abs(numerator), abs(denominator));
numerator /= gcdVal;
denominator /= gcdVal;
}
public:
Rational(int num = 0, int denom = 1) : numerator(num), denominator(denom) {
if (denom == 0) {
cout << "Denominator cannot be zero. Setting to 1." << endl;
denominator = 1;
}
reduce();
}
int getNumerator() const {
return numerator;
}
int getDenominator() const {
return denominator;
}
Rational add(const Rational &other) const {
int newNumerator = numerator * other.denominator + other.numerator * denominator;
int newDenominator = denominator * other.denominator;
return Rational(newNumerator, newDenominator);
}
Rational subtract(const Rational &other) const {
int newNumerator = numerator * other.denominator - other.numerator * denominator;
int newDenominator = denominator * other.denominator;
return Rational(newNumerator, newDenominator);
}
Rational multiply(const Rational &other) const {
int newNumerator = numerator * other.numerator;
int newDenominator = denominator * other.denominator;
return Rational(newNumerator, newDenominator);
}
Rational divide(const Rational &other) const {
if (other.numerator == 0) {
cout << "Cannot divide by zero." << endl;
return Rational(numerator, denominator);
}
int newNumerator = numerator * other.denominator;
int newDenominator = denominator * other.numerator;
return Rational(newNumerator, newDenominator);
}
bool equals(const Rational &other) const {
return (numerator == other.numerator && denominator == other.denominator);
}
double doubleValue() const {
return static_cast<double>(numerator) / denominator;
}
void print() const {
if (denominator == 0) {
cout << "Inf" << endl;
} else if (denominator == 1) {
cout << numerator << endl;
} else {
cout << numerator << "/" << denominator << endl;
}
}
};
int main() {
int x, y;
char ignore;
cin >> x >> ignore >> y;
Rational a(x, y);
cin >> x >> ignore >> y;
Rational b(x, y);
Rational c;
a.print();
b.print();
c = a.add(b);
c.print();
c = a.subtract(b);
c.print();
c = a.multiply(b);
c.print();
c = a.divide(b);
c.print();
cout << (a.equals(b) ? "a==b" : "a!=b") << endl;
cout << b.doubleValue() << endl;
return 0;
}
10.
【描述】
小明是一个熊孩子,他很想知道某一个日期是星期几。他知道你正在学习C++,所以想请你写一个程序,实现一个Date类。Date类的定义如下:
class Date { public: Date(int year, int month, int day); int getWeekday() const; private: int year; int month; int day; };
成员变量year、month、day分别代表年月日。现在你要实现Date函数和getWeekday函数,并编写main函数。getWeekday函数,如果日期合法,返回1~7中某个数值,表示星期一到星期天中某一天(其中1为星期一),如果日期不合法,则返回-1。
【输入】
输入包含多组数据。每行包括三个整数year(2000≤y≤9999)、month、day。输入数据以0 0 0结束。
【输出】
每组数据输出一行,每行包括一个整数。1表示星期一,7表示星期日,等等,若数据非法,则输出-1。
0 0 0不需输出
【输入示例】
2013 2 26 2013 2 29 0 0 0
【输出示例】
2 -1
#include <iostream>
using namespace std;
// 请在此处编写Date类
class Date {
private:
int year;
int month;
int day;
bool isValid() {
if (year < 2000 || year > 9999 || month < 1 || month > 12) {
return false;
}
int daysInMonth[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (month == 2) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
daysInMonth[2] = 29;
}
}
return day > 0 && day <= daysInMonth[month];
}
int calculateWeekday() {
int totalDays = 0;
for (int y = 2000; y < year; ++y) {
totalDays += (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? 366 : 365;
}
int daysInMonth[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
daysInMonth[2] = 29;
}
for (int m = 1; m < month; ++m) {
totalDays += daysInMonth[m];
}
totalDays += day;
return (6 + totalDays - 1) % 7 ;
}
public:
Date(int y, int m, int d) : year(y), month(m), day(d) {}
int getWeekday() {
if (isValid()) {
return calculateWeekday();
} else {
return -1;
}
}
};
int main() {
int year, month, day;
while(cin >> year >> month >> day) {
if(year == 0 && month == 0 && day == 0)
break;
Date d(year, month, day);
cout << d.getWeekday() << endl;
}
return 0;
}