一、课内实验题(共10小题,100分)
题型得分 | 100 |
-
【描述】
声明并实现一个Point类,表示直角坐标系中的一个点。Point类包括:
double类型的私有数据成员x和y,表示坐标。
无参(默认)构造函数,将坐标设置为原点。
有参构造函数,将坐标设置为给定的参数。
访问器函数getX和getY,分别用于访问点的x坐标和y坐标。
【输入】
【输出】0,0 4,5
【来源】(0,0) (4,5)
《程序设计基础——以C++为例》第5章实验1。
(10分)我的答案:// 请在此处编写Point类 class Point { public: Point(double x, double y) { getx = x; gety = y; } double getX() { return getx; } double getY() { return gety; } private: double getx;double gety; };
题目得分 10 参考答案:#include <iostream> using namespace std; class Point { public: Point() { x = y = 0; } Point(double x, double y) { this->x = x; this->y = y; } double getX() const { return x; } double getY() const { return y; } private: double x; double 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; }
-
【描述】
声明并实现一个Rectangle类,表示矩形。Rectangle类包括:
double类型的私有数据成员width和height,表示矩形的宽和高。
带默认参数的构造函数,将矩形的宽和高设置为给定的参数。宽和高的默认参数值为1。
更改器函数setWidth和setHeight,分别用于修改矩形的宽和高。
访问器函数getWidth和getHeight,分别用于访问矩形的宽和高。
成员函数computeArea,返回矩形的面积。
成员函数computePerimeter,返回矩形的周长。
【输入】
【输出】5 40 10 3.5
【来源】200 90 35 27
《程序设计基础——以C++为例》第5章实验2。
(10分)我的答案:// 请在此处编写Rectangle类 class Rectangle { public: Rectangle(double w=1, double h=1) { width = w; height = h; } void setWidth(double w); void setHeight(double h); double getWidth(); double getHeight(); double computeArea(); double computePerimeter(); private: double width, height; }; void Rectangle::setWidth(double w) { width = w; } void Rectangle::setHeight(double h) { height = h; } double Rectangle::computeArea() { return height * width; } double Rectangle::getWidth() { return width; } double Rectangle::getHeight() { return height; } double Rectangle::computePerimeter() { return (height + width) * 2; }
题目得分 10 参考答案:#include <iostream> using namespace std; class Rectangle { public: Rectangle(double newWidth = 1, double newHeight = 1) { width = newWidth; height = newHeight; } void setWidth(double newWidth) { width = newWidth; } void setHeight(double newHeight) { height = newHeight; } double getWidth() const { return width; } double getHeight() const { return height; } double computeArea() const { return width * height; } double computePerimeter() const { return 2 * (width + height); } private: double width; double height; }; int main() { double width, height; cin >> widh >> 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; }
-
【描述】
声明并实现一个Cylinder类,表示圆柱体。Cylinder类包括:
double类型的私有数据成员radius和height,分别表示圆柱体底半径和高。
带默认参数的构造函数,将圆柱体底半径和高设置为给定的参数。半径和高的默认参数值为1。
访问器函数,分别用于访问圆柱体底半径和高。
成员函数computeVolume,返回圆柱体体积。
成员函数computeSurfaceArea,返回圆柱体表面积。
假设PI为3.14159。
【输入】
输入圆柱体的底半径和高。
【输出】
输出圆柱体的体积和表面积。
【输入示例】
【输出示例】4 8
【来源】402.124 301.593
《程序设计基础——以C++为例》第5章实验3。
(10分)我的答案:// 请在此处编写Cylinder类 class Cylinder { public: Cylinder(double r = 1, double h = 1) { radius = r; height = h; } double computeVolume(); double computeSurfaceArea(); private: double radius, height; }; double Cylinder::computeVolume() { return PI * radius * radius * height; } double Cylinder::computeSurfaceArea(){ return PI * radius * radius*2+2*PI*radius*height; }
题目得分 10 参考答案:#include <iostream> using namespace std; const double PI = 3.14159; class Cylinder { public: Cylinder(double radius = 1, double height = 1) { this->radius = radius; this->height = height; } 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); } private: double radius; double height; }; int main() { double radius, height; cin >> radius >> height; Cylinder cylinder(radius, height); cout << cylinder.computeVolume() << endl; cout << cylinder.computeSurfaceArea() << endl; return 0; }
-
【描述】
声明并实现一个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%
假设年利率为4.5%,则以4.5作为输入值。
月利率=年利率/12
【来源】《程序设计基础——以C++为例》第5章实验4。
(10分)我的答案:class Account { public: Account(string idd, string namee, double balancee, double annuallnterestRatee) { id = idd; name = namee; balance = balancee; annuallnterestRate = annuallnterestRatee; } void setId(string idd); void setName(string namee); void setBalance(double balancee); void setAnnuallnterestRate(double annuallnterestRatee); string getId(); string getName(); double getBalance(); double getAnnuallnterestRate(); void withdraw(double money); void deposit(double money); double computeMonthlyInterestRate(); void print(); private: string id, name; double balance, annuallnterestRate; }; void Account::setId(string idd) { id = idd; } void Account::setName(string namee) { name = namee; } void Account::setBalance(double balancee) { balance = balancee; } void Account::setAnnuallnterestRate(double annuallnterestRatee) { annuallnterestRate = annuallnterestRatee; } string Account::getId() { return id; } string Account::getName() { return name; } double Account::getBalance() { return balance; } double Account::getAnnuallnterestRate() { return annuallnterestRate; } void Account::withdraw(double money) { balance-= money; } void Account::deposit(double money) { balance += money; } double Account::computeMonthlyInterestRate() { return annuallnterestRate / 12.0; } void Account::print() { cout << id << endl << name << endl << balance << endl << computeMonthlyInterestRate() << "%"; }
题目得分 10 参考答案:#include <iostream> #include <string> using namespace std; class Account { public: Account(string id, string name, double balance, double annualInterestRate); void setId(string id); void setName(string name); void setBalance(double balance); void setAnnualInterestRate(double annualInterestRate); string getId() const; string getName() const; double getBalance() const; double getAnnualInterestRate() const; bool withdraw(double amount); void deposit(double amount); double getMonthlyInterestRate() const; void print() const; private: string id; string name; double balance; double annualInterestRate; }; Account::Account(string id, string name, double balance, double annualInterestRate) :id(id), name(name), balance(balance), annualInterestRate(annualInterestRate) { } void Account::setId(string id) { this->id = id; } void Account::setName(string name) { this->name = name; } void Account::setBalance(double balance) { this->balance = balance; } void Account::setAnnualInterestRate(double annualInterestRate) { this->annualInterestRate = annualInterestRate; } string Account::getId() const { return id; } string Account::getName() const { return name; } double Account::getBalance() const { return balance; } double Account::getAnnualInterestRate() const { return annualInterestRate; } bool Account::withdraw(double amount) { if(amount <= balance) { balance -= amount; return true; } else return false; } void Account::deposit(double amount) { balance += amount; } double Account::getMonthlyInterestRate() const { return annualInterestRate / 12; } void Account::print() const { cout << id << endl; cout << name << endl; cout << balance << endl; cout << getMonthlyInterestRate() << "%" << 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; }
-
【描述】
声明并实现一个Loan类,表示贷款。Loan类包括:
double类型的私有数据成员loanAmount,表示贷款额。double类型的私有数据成员annualInterestRate,表示贷款年利率。int类型的私有数据成员numberOfYears,表示贷款年限。
有参构造函数,将贷款额、贷款年利率、贷款年限设置为给定的参数。
更改器函数setLoanAmount、setAnnualInterestRate和setNumberOfYears,分别用于修改贷款额、贷款年利率、贷款年限。
访问器函数getLoanAmount、getAnnualInterestRate和getNumberOfYears,分别用于访问贷款额、贷款年利率、贷款年限。
成员函数getMonthlyPayment,返回月还款额。
成员函数getTotalPayment,返回总还款额。
【输入】
输入贷款额、贷款年利率、贷款年限。
【输出】
月还款额和总还款额。
【输入示例】
【输出示例】60000 6.25 15
【提示】514.454 92601.7
假设年利率为6.25%,则以6.25作为输入值。
计算月还款额的公式如下:
【来源】
《程序设计基础——以C++为例》第5章实验5。 (10分)我的答案:// 请在此处编写Loan类 class Loan { public: Loan(double loanAmount, double annuallnterestRate, int numberOfYears) { this->loanAmount = loanAmount;this->annuallnterestRate = annuallnterestRate;this->numberOfYears = numberOfYears; } void setLoanAmount(double loanAmount){ this->loanAmount = loanAmount; } void setAnnuallnterestRate(double annuallnterestRate) {this->annuallnterestRate = annuallnterestRate; } void setNumberOfYears(int numberOfYears) { this->numberOfYears = numberOfYears; } double getLoanAmount() { return loanAmount; } double getAnnuallnterestRate() { return annuallnterestRate; } double getNumberOfYears() { return numberOfYears; } double getMonthlyPayment(); double getTotalPayment(); private: double loanAmount, annuallnterestRate; int numberOfYears; }; double Loan::getMonthlyPayment() { double monthlyInterestRate = annuallnterestRate*0.01 / 12.0; return (monthlyInterestRate * loanAmount) / (1 - 1 / pow((1 + monthlyInterestRate), numberOfYears * 12)); } double Loan::getTotalPayment() { return getMonthlyPayment() * 12 * numberOfYears; }
题目得分 10 参考答案:#include <iostream> #include <cmath> using namespace std; class Loan { public: Loan(double loanAmount, double annualInterestRate, int numberOfYears); void setLoanAmount(double newLoanAmount); void setAnnualInterestRate(double newAnnualInterestRate); void setNumberOfYears(int newNumberOfYears); double getLoanAmount() const; double getAnnualInterestRate() const; int getNumberOfYears() const; double getMonthlyPayment(); double getTotalPayment(); private: double loanAmount; double annualInterestRate; int numberOfYears; }; Loan::Loan(double newLoanAmount, double newAnnualInterestRate, int newNumberOfYears) { loanAmount = newLoanAmount; annualInterestRate = newAnnualInterestRate; numberOfYears = newNumberOfYears; } void Loan::setLoanAmount(double newLoanAmount) { loanAmount = newLoanAmount; } void Loan::setAnnualInterestRate(double newAnnualInterestRate) { annualInterestRate = newAnnualInterestRate; } void Loan::setNumberOfYears(int newNumberOfYears) { numberOfYears = newNumberOfYears; } double Loan::getLoanAmount() const { return loanAmount; } double Loan::getAnnualInterestRate() const { return annualInterestRate; } int Loan::getNumberOfYears() const { return numberOfYears; } double Loan::getMonthlyPayment() { double monthlyInterestRate = annualInterestRate / 1200; return loanAmount * monthlyInterestRate / (1 - (pow(1 / (1 + monthlyInterestRate), numberOfYears * 12))); } double Loan::getTotalPayment() { 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; }
-
【描述】
声明并实现一个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
《程序设计基础——以C++为例》第5章实验6。 (10分)我的答案:class Time{ public: Time(int hour=0, int minute=0, int second=0){ if (hour < 0 || hour>24 || minute < 0 || minute>60 || second < 0 || second>60) throw invalid_argument("Invalid argument!"); else { this->hour = hour; this->minute = minute; this->second = second; } } int getHour() { return hour; } void setHour(int hour){this->hour = hour;} int getMinute(){ return minute;} void setMinute(int minute){this->minute = minute; } int getSecond(){return second; } void setSecond(int second){ this->second = second; } void setTime(int hour, int minute, int second) { this->hour = hour; this->minute = minute; this->second = second; } void printTime24(){ if(hour==24){ printf("00:%02d:%02d\n",minute,second); }else{ printf("%02d:%02d:%02d\n", hour, minute, second); } } void printTime12(){ if (hour < 12){ if(hour==0){ printf("AM12:%02d:%02d\n",minute,second); }else{ printf("AM%d:%02d:%02d\n", hour, minute, second); } }else { if(hour==24){ printf("AM12:%02d:%02d\n",minute,second); }else{ if(hour>12){ printf("PM%d:%02d:%02d\n", hour-12, minute, second); }else printf("PM%d:%02d:%02d\n", hour, minute, second); } } } void tick(){ if (second == 59){ second = 0; minute++; if (minute == 60){ minute = 0; hour++; if (hour == 25) { hour = 0; } } } } private: int hour=0; int minute = 0; int second = 0; };
题目得分 10 参考答案:#include <iostream> #include <iomanip> #include <stdexcept> using namespace std; class Time { public: Time(int hour = 0, int minute = 0, int second = 0); void setTime(int hour, int minute, int second); void setHour(int hour); void setMinute(int minute); void setSecond(int second); int getHour() const; int getMinute() const; int getSecond() const; void printTime24() const; void printTime12() const; void tick(); private: int hour; int minute; int second; }; Time::Time(int hour, int minute, int second) { setTime(hour, minute, second); } void Time::setTime(int hour, int minute, int second) { setHour(hour); setMinute(minute); setSecond(second); } void Time::setHour(int hour) { if(hour >= 0 && hour < 24) this->hour = hour; else throw invalid_argument("Invalid argument!"); } void Time::setMinute(int minute) { if(minute >= 0 && minute < 60) this->minute = minute; else throw invalid_argument("Invalid argument!"); } void Time::setSecond(int second) { if(second >= 0 && second < 60) this->second = second; else throw invalid_argument("Invalid argument!"); } int Time::getHour() const { return hour; } int Time::getMinute() const { return minute; } int Time::getSecond() const { return second; } void Time::printTime24() const { cout << setfill('0') << setw(2) << hour << ":" << setw(2) << minute << ":" << setw(2) << second << endl; } void Time::printTime12() const { cout << (hour < 12 ? "AM" : "PM") << ((hour == 0 || hour == 12) ? 12 : hour % 12) << ":" << setfill('0') << setw(2) << minute << ":" << setw(2) << second << endl; } void Time::tick() { ++second; if(second >= 60) { second -= 60; ++minute; if(minute >= 60) { minute -= 60; ++hour; hour %= 24; } } } 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; }
-
【描述】
自定义异常类NegativeNumberException,表示对负数执行操作时出现的异常,如计算负数的平方根。该类有一个string类型的私有数据成员message,用来存放异常信息;一个无参(默认)构造函数和一个有参构造函数,用来设置异常信息;成员函数what,用来显示异常信息。在main函数中,让用户输入某个数,并调用squareRoot函数,计算该数的平方根。如果输入的是负数,squareRoot函数将抛出NegativeNumberException异常,否则返回该数的平方根。
【输入】
输入一个数。
【输出】
输出该数的平方根或者输出错误信息“Invalid argument!”。
【输入示例】
【输出示例】-8
【来源】Invalid argument!
《程序设计基础——以C++为例》第5章实验7。 (10分)我的答案:// 请在此处分别编写NegativeNumberException类和squareRoot函数 class NegativeNumberException{ public: NegativeNumberException(string str="Invalid argument!"){ this->str=str; } string what(){ return str; } private: string str; }; double squareRoot(double value){ if(value<0){ throw NegativeNumberException(); }else{ return sqrt(value); } }
题目得分 10 参考答案:#include <iostream> #include <string> #include <cmath> using namespace std; class NegativeNumberException { public: NegativeNumberException() { message = "Exception!"; } NegativeNumberException(string msg) { message = msg; } string what() { return message; } private: string message; }; double squareRoot(double value) { if(value < 0) throw NegativeNumberException("Invalid argument!"); return sqrt(value); } int main() { double value; cin >> value; try { cout << squareRoot(value) << endl; } catch(NegativeNumberException &ex) { cout << ex.what() << endl; } return 0; }
-
【描述】
(10分)
自定义异常类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”。
【来源】
《程序设计基础——以C++为例》第5章实验8。我的答案:class TriangleException{ public: TriangleException(string str){ this->str=str; } string what(){ return str; } private: string str; }; class Triangle{ public: Triangle(double side1=1,double side2=1,double side3=1){ if(check(side1)&&check(side2)&&check(side3)){ if(!isValid(side1,side2,side3))throw TriangleException("Don't make a triangle"); else this->side1=side1;this->side2=side2;this->side3=side3; }else{ throw TriangleException("Negative side"); } } void setSide1(double side1){ this->side1=side1;} double getSide1(){return side1;} void setSide2(double side2){ this->side2=side2;} double getSide2(){return side2;} void setSide3(double side3){ this->side3=side3;} double getSide3(){return side3;} double computeArea(){return ((1.0/4.0)*sqrt((side1+side2+side3)*(side1+side2-side3)*(side1+side3-side2)*(side2+side3-side1)));} double computePerimeter(){return (side1+side2+side3);} private: double side1,side2,side3; bool isValid(double side1,double side2,double side3){bool ans=(side1<(side2+side3)&&side2<(side1+side3)&&side3<(side2+side1))?true:false;return ans;} bool check(double side){bool ans=(side<=0)?false:true;return ans;} };
题目得分 10 参考答案:#include <iostream> #include <string> #include <cmath> using namespace std; class TriangleException { public: TriangleException() { message = "Exception"; } TriangleException(string msg) { message = msg; } string what() { return message; } private: string message; }; class Triangle { public: Triangle(double side1 = 1, double side2 = 1, double side3 = 1); void setSide1(double side1); void setSide2(double side2); void setSide3(double side3); double getSide1() const; double getSide2() const; double getSide3() const; double computeArea() const; double computePerimeter() const; private: double side1; double side2; double side3; bool isValid(double side1, double side2, double side3) const; bool check(double side) const; }; Triangle::Triangle(double newSide1, double newSide2, double newSide3) { if(!check(newSide1)) throw TriangleException("Negative side"); if(!check(newSide2)) throw TriangleException("Negative side"); if(!check(newSide3)) throw TriangleException("Negative side"); if(!isValid(newSide1, newSide2, newSide3)) throw TriangleException("Don't make a triangle"); side1 = newSide1; side2 = newSide2; side3 = newSide3; } void Triangle::setSide1(double newSide1) { if(!check(newSide1)) throw TriangleException("Negative side"); if(!isValid(newSide1, side2, side3)) throw TriangleException("Don't make a triangle"); side1 = newSide1; } void Triangle::setSide2(double newSide2) { if(!check(newSide2)) throw TriangleException("Negative side"); if(!isValid(side1, newSide2, side3)) throw TriangleException("Don't make a triangle"); side2 = newSide2; } void Triangle::setSide3(double newSide3) { if(!check(newSide3)) throw TriangleException("Negative side"); if(!isValid(side1, side2, newSide3)) throw TriangleException("Don't make a triangle"); side3 = newSide3; } double Triangle::getSide1() const { return side1; } double Triangle::getSide2() const { return side2; } double Triangle::getSide3() const { return side3; } double Triangle::computeArea() const { double p = 0.5 * (side1 + side2 + side3); return sqrt(p * (p - side1) * (p - side2) * (p - side3)); } double Triangle::computePerimeter() const { return side1 + side2 + side3; } bool Triangle::isValid(double side1, double side2, double side3) const { return (side1 + side2 > side3) && (side1 + side3 > side2) && (side2 + side3 > side1); } bool Triangle::check(double side) const { return side > 0; } 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; }
-
【描述】
有理数是由分子和分母组成的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
《程序设计基础——以C++为例》第5章实验9。
(10分)我的答案:class Rational{ public: Rational(int numerator=0,int denominator=1){ int ans=1; if(denominator!=0){ ans=gcd(numerator,denominator); } this->numerator =numerator/ans; this->denominator=denominator/ans; } int getDenominator(){return denominator;} int getNumerator(){return numerator;} void print(){ if(denominator==0){ cout<<"Inf"<<endl; }else if(numerator%denominator==0){ cout<<numerator/(denominator*1.0)<<endl; }else{ int ans=1; if(denominator!=0){ ans=gcd(numerator,denominator); } numerator =numerator/ans; denominator=denominator/ans; if(denominator<0){ cout<<"-"<<numerator<<"/"<<-denominator<<endl; }else{ cout<<numerator<<"/"<<denominator<<endl; } } } Rational add(Rational b); Rational subtract(Rational b); Rational multiply(Rational b); Rational divide(Rational b); bool equals(Rational b){bool ans=(this->denominator==b.denominator&&this->numerator==b.numerator)?true:false;return ans;} double doubleValue(){return (float)numerator/(float)denominator;} private: int numerator,denominator; static int gcd(int a,int b){ return b==0? a:gcd(b,a%b); } }; Rational Rational::add(Rational b){// + Rational c(numerator,denominator); c.numerator=this->denominator*b.numerator+this->numerator*b.denominator; c.denominator=this->denominator*b.denominator; return c; } Rational Rational::subtract(Rational b){// - Rational c(numerator,denominator); c.numerator=this->numerator*b.denominator-this->denominator*b.numerator; c.denominator=this->denominator*b.denominator; return c; } Rational Rational::multiply(Rational b){// * Rational c(numerator,denominator); c.numerator=this->numerator*b.numerator ; c.denominator=this->denominator*b.denominator; return c; } Rational Rational::divide(Rational b){// / Rational c(numerator,denominator); c.numerator=this->numerator*b.denominator; c.denominator=this->denominator*b.numerator; return c; }
题目得分 10 参考答案:#include <iostream> using namespace std; class Rational { public: Rational(int n = 0, int d = 1); int getNumerator() const; int getDenominator() const; Rational add(const Rational &right); Rational subtract(const Rational &right); Rational multiply(const Rational &right); Rational divide(const Rational &right); bool equals(const Rational &right); double doubleValue() const; void print() const; private: int numerator; // 分子 int denominator; // 分母 int gcd(int n, int d); // 求最大公约数 }; Rational::Rational(int n, int d) { int g = gcd(n, d); if(d < 0) { n = -n; d = -d; } numerator = n / g; denominator = d / g; } int Rational::getNumerator() const { return numerator; } int Rational::getDenominator() const { return denominator; } Rational Rational::add(const Rational &right) { int n = numerator * right.denominator + denominator * right.numerator; int d = denominator * right.denominator; return Rational(n, d); } Rational Rational::subtract(const Rational &right) { int n = numerator * right.denominator - denominator * right.numerator; int d = denominator * right.denominator; return Rational(n, d); } Rational Rational::multiply(const Rational &right) { int n = numerator * right.numerator; int d = denominator * right.denominator; return Rational(n, d); } Rational Rational::divide(const Rational &right) { int n = numerator * right.denominator; int d = denominator * right.numerator; return Rational(n, d); } bool Rational::equals(const Rational &right) { return (numerator == right.numerator) && (denominator == right.denominator); } double Rational::doubleValue() const { return static_cast<double>(numerator) / denominator; } void Rational::print() const { if(denominator == 0) cout << "Inf" << endl; else { cout << numerator; if(numerator != 0 && denominator != 1) cout << "/" << denominator << endl; else cout << endl; } } int Rational::gcd(int m, int n) { if((m == 0) && (n == 0)) return 0; if(m == 0) return n; if(n == 0) return m; if(m < 0) m = -m; if(n < 0) n = -n; int r; while(true) { r = m % n; if(r == 0) break; m = n; n = r; } return n; } 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; }
-
【描述】
小明是一个熊孩子,他很想知道某一个日期是星期几。他知道你正在学习C++,所以想请你写一个程序,实现一个Date类。Date类的定义如下:
成员变量year、month、day分别代表年月日。现在你要实现Date函数和getWeekday函数,并编写main函数。getWeekday函数,如果日期合法,返回1~7中某个数值,表示星期一到星期天中某一天(其中1为星期一),如果日期不合法,则返回-1。class Date { public: Date(int year, int month, int day); int getWeekday() const; private: int year; int month; int day; };
【输入】
输入包含多组数据。每行包括三个整数year(2000≤y≤9999)、month、day。输入数据以0 0 0结束。
【输出】
每组数据输出一行,每行包括一个整数。1表示星期一,7表示星期日,等等,若数据非法,则输出-1。
0 0 0不需输出
【输入示例】
【输出示例】2013 2 26 2013 2 29 0 0 0
【提示】2000年1月1日是星期六。2 -1
求星期几:(6 + 2000年1月1日至输入日期的天数 - 1)% 7 + 1
(10分)我的答案:class Date{ public: Date(int year,int month,int day); int getWeekday() const; private: int year,month,day; }; Date::Date(int year,int month,int day){ this->year=year;this->month=month;this->day=day; } int Date::getWeekday() const { int sum = 0; if(this->month>12){ return -1; } switch(this->month){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: if (this->day > 31) { return -1; } break; case 2: if ((this->year%100!=0&&this->year%4==0)||(this->year%400 == 0)) { if (this->day > 29) { return -1; } } else if (this->day > 28) { return -1; } break; default: if (this->day > 30) { return -1; } } for (int i = 2000; i < this->year; i++) { if ((i%100!=0&&i%4==0)||(i%400 == 0)) { sum += 366; } else { sum += 365; } } for (int i = 1; i < this->month; i++) { switch(i){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: sum += 31; continue; case 2: if ((this->year%100!=0&&this->year%4==0)||(this->year%400 == 0)) { sum+=29; }else{ sum+=28; } continue; default: sum += 30; } } sum += this->day -1; sum=(6 + sum-1) % 7 + 1; return sum; }
题目得分 10 参考答案:#include <iostream> using namespace std; class Date { public: Date(int year, int month, int day); int getWeekday() const; private: int year; int month; int day; }; bool isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } Date::Date(int year, int month, int day) { this->year = year; this->month = month; this->day = day; } int Date::getWeekday() const { const int DAYS_PER_MONTH[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; if(year < 2000 || year > 9999) return -1; if(month < 1 || month > 12) return -1; if(day < 1 || day > DAYS_PER_MONTH[month]) return -1; int sum = 0; // 处理年 for(int i = 2000; i < year; ++i) { if(isLeapYear(i)) sum += 366; else sum += 365; } // 处理月 for(int i = 1; i < month; ++i) sum += DAYS_PER_MONTH[i]; if(isLeapYear(year)) if(month > 2 || month == 2) sum += 1; // 处理日 sum += day - 1; // 除去2000年1月1日 return (6 + sum - 1) % 7 + 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; }