【免费下载】第三章 面向对象程序设计答案
- 格式:pdf
- 大小:206.96 KB
- 文档页数:7
面向对象程序设计课后题答案第二章C++概述【2.6】D【2.7】D【2.8】A【2.9】A【2.10】B【2.11】A【2.12】C【2.13】B【2.14】D【2.15】C【2.16】D【2.17】C【2.18】程序的运行结果:101【2.19】程序的运行结果:10 10【2.20】程序的运行结果:1020【2.22】编写一个C++风格的程序,用动态分配空间的方法计算Fibonacci数列的前20项并存储到动态分配的空间中。
#include <iostream.h>int main(){int *p,i;p[0]=1;p[1]=1;for(i=2;i<20;i++){p[i]=p[i-1]+p[i-2];}for(i=0;i<20;i++){cout<<p[i]<<endl;}return 0;}【2.23】编写一个C++风格的程序,建立一个被称为sroot()的函数,返回其参数的二次方根。
重载sroot()3次,让它返回整数、长整数与双精度数的二次方根。
#include <iostream.h>#include<math.h>double sroot(int m){return sqrt(m);}double sroot(long m){return sqrt(m);}double sroot(double m){return sqrt(m);}int main()cout<<"sroot(145)="<<sroot(145)<<endl;cout<<"sroot(123456)="<<sroot(123456)<<endl;cout<<"sroot(1.44)="<<sroot(1.44)<<endl;return 0;}【2.24】编写一个C++风格的程序,解决百钱问题:将一元人民币兑换成1、2、5分的硬币,有多少种换法?#include <iostream.h>int main(){int k=0;for(int i=0;i<=20;i++){for(int j=0;j<=50;j++){if(100-5*i-2*j>=0){k++;}}}cout<<"将一元人民币兑换成1、2、5分的硬币,共有"<<k<<"种换法"<<endl;return 0;}【2.25】编写一个C++风格的程序,输入两个整数,将它们按由小到大的顺序输出。
C++第三章课后答案C++第三章习题及答案1、什么是结构化程序设计?它有什么优缺点?所谓结构化程序设计,是一种自顶而下、逐步求精的模块化程序设计方法。
2、什么是对象?什么是类?简述对象与类之间的关系!对象是系统中用来描述客观事物的一个实体,它是用于构成系统的一个基本单位,而系统可以看作是由一系列相互作用的对象组成。
类定义了同类对象的公共属性和行为,属性用数据结构表示,行为用函数表示!《类=数据结构+对数据进行操作的函数》。
对象和类的关系相当于元素和集合的关系、变量和变量的“数据类型”的关系。
从程序设计的角度来说,类是一种复杂的自定义数据类型,对象是属于这种数据类型的变量。
3、什么是面向对象程序设计?面向对象程序设计方法具有哪些基本特征?请比较面向对象程序设计和面向对象过程程序设计有何异同?4、何谓成员变量?何谓成员函数?C++将对象的属性抽象为数据成员,将对象的行为抽象为成员函数。
5、C++中结构和类之间有何异同?结构在默认情况下的成员是公共的,而类在默认情况下的成员是私有的。
在C++中,结构是特殊的类。
6、在C++中如何定义类?如何实现定义的类?如何利用类申明对象?7、类的成员的访问权限有哪几种?请说明它们分别有什么作用?三种,privte:类的私有成员,只能被本类的成员函数访问或调用。
Public:公有成员,可以被本类的成员或其他类的成员函数(通过对象)访问或调用。
Protected:保护成员,可以被本类的成员函数或派生类的成员函数访问或调用。
8、何谓构造函数?何谓析构函数?请说明它们分别有什么作用?构造函数:不需要用户程序调用,就能在创建对象时由系统自动调用,其作用是在对象被创建时利用初始值去构造对象,使得在声明对象时就能自动完成对象的初始化。
析构函数:在对象的生存周期即将结束时由系统自动调用的,其作用是用来在对象被删除前做一些清理工作和数据保存工作。
9、如何定义一个内联成员函数?内联函:内联函数必须是和函数体申明在一起,才有效。
实验一熟悉VC++IDE开发环境一、实验目的1、熟悉VC++6.0集成开发环境,熟练掌握VC++6.0项目工作区、各种编辑器、菜单栏和工具栏的使用。
2、掌握如何编辑、编译、连接和运行一个C++程序。
3、通过运行简单的C++程序,初步了解C++源程序的结构和特点。
二、实验要求1、分析下列程序运行的结果。
程序一:#include <iostream.h>int add(int x,int y=8);void main(){ int x=4;cout<<add(x)<<",";cout<<add(x,add(add(x,add(x))))<<endl;}int add(int x,int y){ return x+y;}//12,28程序二:#include <iostream.h>void main(){ int *p,i;i=5;p=&i;i=*p+10;cout<<"i="<<i<<endl;}//i=15程序三:#include <iostream.h>void main(void){ int i=10;int &r=i;r++;cout<<"i="<<i<<", r="<<r<<'\n';i=88;cout<<"i="<<i<<", r="<<r<<'\n';}//i=11,r=11i=88,r=88程序四:#include <iostream.h>int f(int i){ static int k=1;for(;i>0;i--)k +=i;return k;}void main(){ int i;for(i=0;i<5;i++)cout<<f(i)<<" ";}// 1 2 5 11 21程序五:#include <iostream.h>void func();int n=1;void main(){ static int a;int b= -9;cout <<"a:"<<a<<" b:"<<b<<" n:" <<n<<endl;b+=4;func();cout <<"a:"<<a<<" b:"<<b<<" n:"<<n<<endl;n+=10;func();}void func(){ static int a=2; int b=5;a+=2;n+=12;b+=5;cout <<"a:" <<a<<" b:" <<b<<" n:" <<n <<endl;}// a:0 b:-9 n:1a:4 b:10 n:13a:0 b:-5 n:13a:6 b:10 n:35实验二C++对C的扩充一、实验目的1、了解在面向对象程序设计过程中C++对C功能的扩充与增强,并善于在编写程序的过程中应用这些新功能。
学号:姓名:第三章面向对象程序设计作业一、判断题1、一个Java源程序可有多个类,但只仅有一个public 类,而且程序名与public 类名相同。
对2、如果类 A 和类B 在同一个包中,则除了私有成员外,类 A 可以访问类 B 中所有的成员。
对3、接口中的成员变量全部为常量,方法为抽象方法。
对4、抽象类可以有构造方法,可以直接实例化。
错5、对static 方法的调用可以不需要类实例。
对6、包含抽象方法的类一定是抽象类。
对7、方法中的形参可以和方法所属类的属性同名。
对8、接口无构造器,不能有实例,也不能定义常量。
错9、类的实例对象的生命周括实例对象的创建、使用、废弃、垃圾的回收。
对10、Java应用程序的入口main 方法只有一种定义法。
对二、选择题1、下列答案正确的是( A )A) 在同一个Java 源文件中可以包含多个类,只能有一个被声明为publicB) 在同一个Java 源文件中只能包含一个类,并被声明为publicC) 在同一个Java 源文件中可以包含多个类,都可以被声明为publicD) 在同一个Java 源文件中可以包含多个类,只能有一个被声明为default2、Java实现动态多态性是通过( B )实现的。
A) 重载B) 覆盖C) 接口D) 抽象类3、下列哪一个是正确的方法重载描述( A )A) 重载方法的参数类型必须不同B) 重载方法的参数名称必须不同C) 返回值类型必须不同D) 修饰词必须不同4、final 关键字不可以用来修饰( D )A) 类B) 成员方法C) 域D) 接口5、接口的所有成员方法都具有( B )属性A) private, final B) public, abstractC) static, protected D) static6、Java的封装性是通过( A )实现的A) 访问控制B) 设计内部类C) 静态域和静态方法D) 包7、下列接口或类不属于java.util.* 包的是( D )A) Collection B)Vector C) Map D) Integer8、下述哪一组方法,是一个类中方法重载的正确写法?( A )A) int addValue( int a, int b ){return a+b;}float addValue ( float a, float b) {return a+b;}B) int addValue (int a, int b ){value=a+b; }float addValue ( int a, int b) {return (float)(a+b);}C) int addValue( int a, int b ){return a+1;}int addValue ( int a, int b) {return a+b;}D) int addValue( int a, int b ) {return a+b;}int addValue ( int x, int y ) {return x+y;}9、下列说法哪个是正确的?( C )A) 子类不能定义和父类同名同参数的方法B) 子类只能继承父类的方法,而不能重载C) 重载就是一个类中有多个同名但有不同形参和方法体的方法D) 子类只能覆盖父类的方法,而不能重载10、对于下列代码:public class Parent {public int addValue( int a, int b) {int s;s = a+b;return s;}}class Child extends Parent {}下述哪个方法不可以加入类Child? ( B )A) public int addValue( int a, int b,int c ){// do something...}B) public void addV alue (int a, int b ){// do something...}C) public int addValue( int a ){// do something...}D) public int addValue( int a, int b ) {//do something...}11、以下程序段输出结果的是( B )public class A implements B {public static void main(String args[]) {int i;A c1 = new A();i= c1.k;System.out.println("i="+i);}}interface B {int k = 10;}A) i=0 B) i=10 C) 程序有编译错误D) i=true12、阅读下面的程序,输出结果是( B )public class TestDemo {int m=5;public void some(int x) {m=x;}public static void main(String args []) {new Demo().some(7);}}class Demo extends TestDemo {int m=8;public void some(int x) {super.some(x);System.out.println(m);}}A) 5 B) 8 C) 7 D) 编译错误13、下述哪个说法是不正确的?( A )A) 局部变量在使用之前无需初始化,因为有该变量类型的默认值B) 类成员变量由系统自动进行初始化,也无需初始化C) 参数的作用域就是所在的方法D) for 语句中定义的变量,当for 语句执行完时,该变量就消亡了14、下述那一个保留字不是类及类成员的访问控制符。
第三部分面向对象程序设计1、引用数据类型变量具有基本属性为(ABCD)A、变量名B、数据类型C、存储单元D、变量值。
2、面向对象技术的特性是(ACD)A、继承性B、有效性C、多态性D、封装性。
3、下列哪个命题为真?(C)A、所有类都必须定义一个构造函数。
B、构造函数必须有返回值。
C、构造函数可以访问类的非静态成员。
D、构造函数必须初始化类的所有数据成员。
4、关于子类与父类关系的描述正确的是(ACD)A、子类型的数据可以隐式转换为其父类型的数据;B、父类型的数据可以隐式转换为其子类型的数据;C、父类型的数据必须通过显示类型转换为其子类型的数据;D、子类型实例也是父类型的实例对象。
5、下列哪一项说法最好地描述了Java中的对象?(C)A、对象是通过import命令引入到程序中的所有事情B、对象是方法的集合,这些方法在小程序窗口或应用程序窗口中产生图形元素,或者计算和返回值C、对象是一种数据结构,它具有操作数据的方法D、对象是一组具有共同的结构和行为的类6、下面哪个关键字不是用来控制对类成员的访问的?(C)A、publicB、protectedC、defaultD、private7、Java语言正确的常量修饰符应该是(D)A、finalB、static finalC、staticD、public static final;8、接口的所有成员域都具有public 、static和final 属性。
9、接口的所有成员方法都具有public 和abstract 属性。
10、编译下列源程序会得到哪些文件?(C)class A1{}class A2{}public class B{public static void main(String args[]){}}A) 只有B.classB)只有A1.class和A2.class文件C)有A1.class、A2.class和B.class文件D) 编译不成功11、下列哪种说法是正确的?(A)A、私有方法不能被子类覆盖。
《面向对象程序设计》习题三答案一、单项选择题(本大题共25小题,每小题2分,共50分)1、用“>>”运算符从键盘输入多于一个数据时,各数据之间应使用( D )符号作为分隔符。
A、空格或逗号B、逗号或回车C、逗号或分号D、空格或回车2、C++中声明常量的关键字是( A )。
A、constB、externC、publicD、enum3、以下叙述中正确的是( B )A、使用#define可以为常量定义一个名字,该名字在程序中可以再赋另外的值B、使用const定义的常量名有类型之分,其值在程序运行时是不可改变的C、在程序中使用内置函数使程序的可读性变差D、在定义函数时可以在形参表的任何位置给出缺省形参值4、下列的符号常变量定义中,错误的定义是( C )。
A、const M=10;B、const int M=20;C、const char ch;D、const bool mark=true;5、函数原型语句正确的是( B )。
A、int Function(void a)B、void Function (int);C、int Function(a);D、void int(double a);6、在关键字private后面定义的成员为类的( A )成员。
A、私有B、公用C、保护D、任何7、在一个类的定义中,包含有( C )成员的定义。
A、数据B、函数C、数据和函数D、数据或函数8、在类作用域中能够通过直接使用该类的( D )成员名进行访问。
A、私有B、公用C、保护D、任何9、在关键字public后面定义的成员为类的( B )成员。
A、私有B、公用C、保护D、任何10、类中定义的成员默认为( B )访问属性。
A、publicB、privateC、protectedD、friend11、每个类( C )构造函数。
A、只能有一个B、可以有公用的C、可以有多个D、只可有缺省的12、对类对象成员的初始化是通过构造函数中给出的( B )实现的。
0837一、BCABB DDCBA二、1、答:程序运行的输出结果是:1 2 6 24 1202、3、问题(1):Test3是SuperTest的子类(或SuperTest是Test3的父类,或继承关系)。
问题(2):super指对象的父类(或超类);this指使用它的对象本身(或对对象自己的引用)。
问题(3):程序的输出是:<\ p="">Hi, I am OliveNice to meet you!Age is 7My age is 7My parent"s age is 35<\ p="">4、答:问题(1):new FileOutputStream(“out.txt”)dout.writeInt( ‘0’ + i);dout.close( );new FileInputStream(“out.txt”)din.readInt( )din.close( );问题(2):常被用于读取与存储(读写或输入/输出)基本数据类型的数据。
问题(3):文件out.txt的内容是:0 1 2 3 4 5 6 7 8 9程序在控制台窗口输出:0,1,2,3,4,5,6,7,8,9,三、import java.io.DataOutputStream;import java.io.FileOutputStream;import java.io.IOException;public class TestSort {public static int MAXSIZE = 61;public static void sortInt(int[] arr) { // 采用选择法对一维数组进行排序for (int i = 0; i < arr.length - 1; i++) {int k = i;for (int j = i + 1; j < arr.length; j++)if (arr[j] < arr[k])k = j; // 用k记录最小值的下标if (k > i) { // 在外循环中实施交换arr[i] = arr[i] + arr[k];arr[k] = arr[i] - arr[k];arr[i] = arr[i] - arr[k];}}}public static void main(String args[]) {int score[] = new int[MAXSIZE];try {for (int i = 0; i < MAXSIZE; i++)score[i] = (int) (Math.random() * 100 + 0.5);sortInt(score);DataOutputStream dout = new DataOutputStream(new FileOutputStream(\"score.txt\"));for (int i = 0; i < MAXSIZE; i++) {dout.writeInt(score[i]);System.out.println(score[i]);}dout.close();// 结果保存到文件} catch (IOException e) {System.err.println(\"发生异常:\" + e);e.printStackTrace();}// try-catch结构处理异常}}。
第三章作业3.18某城市为鼓励节约用水,对居民用水量做出如下规定:若每人每月用水量不超过2m*m*m,则按0.3元收费,若大于4 m*m*m按0.3元收费,剩余部分按0.6元收费;若超过4 m*m*m,则其中的2 m*m*m 按0.3元收费,再有2 m*m*m按0.6元收费,剩余部分按1.2元收费。
试编程实现根据每户的月用水量和该户的人数应缴纳的水费。
#include<iostream>using namespace std;double func(int i,double j){double k=j/i,sum;if(k<=2)sum=0.3*j;else if(k>2&&k<=4)sum=0.3*2*i+(j-2*i)*0.6;elsesum=0.3*2*i+0.6*2*i+(j-4*i)*1.2;return sum;}void main(){int n;double a;cout<<"该用户人数:"<<endl;cin>>n;cout<<"该户的用水量"<<endl;cin>>a;cout<<"应交纳水费"<<endl;cout<<func(n,a)<<"yuan"<<endl;}3.20利用迭代公式x(n+1)=(x(n)+a/x(n))/2 其中n=0,1,2,3…,x0=a/2 编程实现从键盘输入任一正数a,求出该正数的平方根#include<iostream>#include"math.h"using namespace std;double func(int i){double x0,x1;x0=i/2;x1=(x0+i/x0)/2;while(abs(x1-x0)>=1e-6){x0=x1;x1=(x0+i/x0)/2;}return x1;}void main(){int a;cout<<"请输入一个正数:"<<endl;cin>>a;cout<<"该正数的平方根为:"<<endl;cout<<func(a)<<endl;}3.22编写程序,把一个字符串插入到另一个字符串中的指定位置。
Chapter 3MORE FLOW OF CONTROL1. Solutions for and Remarks on Selected Programming ProblemsIn order to preserve flexibility of the text, the author has not dealt with classes in this chapter at all. To help those who really want to do things with classes, some of the Programming Projects will be carried out using one or several classes.1. Rock Scissors PaperHere each of two players types in one of strings "Rock", "Scissors", or "Paper". After the second player has typed in the string, the winner of this game is determined and announced.Rules:Rock breaks ScissorsScissors cuts PaperPaper covers RockIf both players give the same answer, then there is no winner.A nice touch would be to keep and report total wins for each player as play proceeds.To find the classes, we note first that there are 2 identical players. These players record the character entered, and keep track of the wins. There is a constructor that sets the total wins to 0. There is a play() member function that prompts for and gets from the keyboard returns one of the characters 'R', 'P', or 'S' for rock, paper and scissors. There is an accessor member function for ch and an incrementor member function for accumulated wins so that a stand alone function int win(ch, ch); can determine who wins and increment the accumulated wins variable.(A better solution would make the wins function a friend of class player so that wins can have access to the each player's private data to determine who wins and update the accumulated wins without the accessor function ch() and incrementWins() function.)Note that I have left a bit of debugging code in the program.class player{public function membersconstructors()play(); // prompts for and gets this player's movechar ch(); // accessorint accumulatedWins(); // accessorincrWins(); // increments win countprivate datacharacter typed inaccumulatedWins};int wins(player user1, player user2);//player1's character is compared to player2's character using accessor // functions.// wins returns// 0 if there no winner// 1 if player 1 wins,// 2 if player 2 wins,//calls the appropriate incrWins() to update the winsNote that once the class is defined and the auxiliary function written, the code “almost writes itself.”//file: //Rock Paper Scissors game//class/object solution#include <iostream>#include <cctype> //for int toupper(int);using namespace std;class Player{public:Player();void play(); //prompts for and gets this player's movechar Ch(); //accessorint AccumulatedWins(); //accessorvoid IncrWins(); //increments win countprivate:char ch; //character typed inint totalWins; //total of wins};Player::Player():totalWins(0)//intializer sets Player::totalWins to 0 {//The body is deliberately empty. This is the preferred C++ idiom. //This function could be written omitting the initializer, and//putting this line in the body://totalWins = 0;}void Player::play(){cout << "Please enter either R)ock, P)aper, or S)cissors."<< endl;cin >> ch;ch = toupper(ch); //no cast needed, ch is declared to be char}char Player::Ch(){return ch;}int Player::AccumulatedWins(){return totalWins;}void Player::IncrWins(){totalWins++;}int wins(Player& user1, Player& user2);// player1's character is compared to player2's character// using accessor functions.// The function wins returns// 0 if there no winner// 1 if player 1 wins,// 2 if player 2 wins,//calls the appropriate IncrWins() to update the winsint wins(Player& user1, Player& user2 ) // this must change user1// and user2{if( ( 'R' == user1.Ch() && 'S' == user2.Ch() )||( 'P' == user1.Ch() && 'R' == user2.Ch() )||( 'S' == user1.Ch() && 'P' == user2.Ch() ) ){// user 1 winsuser1.IncrWins();return 1;}else if( ( 'R' == user2.Ch() && 'S' == user1.Ch() )|| ( 'P' == user2.Ch() && 'R' == user1.Ch() )|| ( 'S' == user2.Ch() && 'P' == user1.Ch() ) ) {// user2 winsuser2.IncrWins();return 2;}else// no winnerreturn 0;}int main(){Player player1;Player player2;char ans = 'Y';while ('Y' == ans){player1.play();player2.play();switch( wins(player1, player2) ){case 0:cout << "No winner. " << endl<< "Totals to this move: " << endl<< "Player 1: " << player1.AccumulatedWins() << endl<< "Player 2: " << player2.AccumulatedWins()<< endl<< "Play again? Y/y continues other quits";cin >> ans;cout << "Thanks " << endl;break;case 1:cout << "Player 1 wins." << endl<< "Totals to this move: " << endl<< "Player 1: " << player1.AccumulatedWins()<< endl<< "Player 2: " << player2.AccumulatedWins()<< endl<< "Play Again? Y/y continues, other quits. "; cin >> ans;cout << "Thanks " << endl;break;case 2:cout << "Player 2 wins." << endl<< "Totals to this move: " << endl<< "Player 1: " << player1.AccumulatedWins()<< endl<< "Player 2: " << player2.AccumulatedWins()<< endl<< "Play Again? Y/y continues, other quits.";cin >> ans;cout << "Thanks " << endl;break;}ans = toupper(ans);}return 0;}A typical run for the class/object solution follows:Please enter either R)ock, P)aper, or S)cissors.RPlease enter either R)ock, P)aper, or S)cissors.Sinside IncrWins()1Player 1 wins.Totals to this move:Player 1: 1Player 2: 0Play Again? Y/y continues, other quits. yThanksPlease enter either R)ock, P)aper, or S)cissors. SPlease enter either R)ock, P)aper, or S)cissors. Pinside IncrWins()2Player 1 wins.Totals to this move:Player 1: 2Player 2: 0Play Again? Y/y continues, other quits. yThanksPlease enter either R)ock, P)aper, or S)cissors. PPlease enter either R)ock, P)aper, or S)cissors. Sinside IncrWins()1Player 2 wins.Totals to this move:Player 1: 2Player 2: 1Play Again? Y/y continues, other quits.yThanksPlease enter either R)ock, P)aper, or S)cissors. PPlease enter either R)ock, P)aper, or S)cissors. PNo winner.Totals to this move:Player 1: 2Player 2: 1Play again? Y/y continues other quits qThanks1. Rock Scissors Paper -- Conventional solution:Here each of two players types in one of strings "Rock", "Scissors", or "Paper". After the second player has typed in the string, the winner of this game is determined and announced.Rules:Rock breaks ScissorsScissors cuts PaperPaper covers RockIf both players give the same answer, then there is no winner.A nice touch would be to keep and report total wins for each player as play proceeds.This is a conventional solution to the problem.//file //conventional solution to the Rock Scissors Paper game#include <iostream> // stream io#include <cctype> // for int toupper(int)using namespace std;int wins(char ch1, char ch2){if( ( 'R' == ch1 && 'S' == ch2 )||( 'P' == ch1 && 'R' == ch2 )||( 'S' == ch1 && 'P' == ch2 ) )return 1; // player 1 winselse if(( 'R' == ch2 && 'S' == ch1 )||( 'P' == ch2 && 'R' == ch1 )||( 'S' == ch2 && 'P' == ch1 ) )return 2; // player 2 winselsereturn 0; // no winner}char play(){char ch;cout << "Please enter either R)ock, P)aper, or S)cissors." << endl; cin >> ch;return toupper(ch); // no cast needed, char is return type}int main(){int wins_1 = 0;int wins_2 = 0;char ch1;char ch2;char ans = 'Y';while ('Y' == ans){ch1 = play();ch2 = play();switch( wins(ch1, ch2) ){case 0:cout << "No winner. " << endl<< "Totals to this move: " << endl<< "Player 1: " << wins_1 << endl<< "Player 2: " << wins_2 << endl<< "Play again? Y/y continues other quits";cin >> ans;cout << "Thanks " << endl;break;case 1:wins_1++;cout << "Player 1 wins." << endl<< "Totals to this move: " << endl<< "Player 1: " << wins_1 << endl<< "Player 2: " << wins_2 << endl<< "Play Again? Y/y continues, other quits. ";cin >> ans;cout << "Thanks " << endl;break;case 2:wins_2++;cout << "Player 2 wins." << endl<< "Totals to this move: " << endl<< "Player 1: " << wins_1 << endl<< "Player 2: " << wins_2 << endl<< "Play Again? Y/y continues, other quits.";cin >> ans;cout << "Thanks " << endl;break;}ans = toupper(ans);}return 0;}A typical run follows for the co nventional solution is essentially the same as for the …class‟ based solution.2. Credit Account problem. -- class/object solutionCompute interest due, total amount due, and minimum payment for a revolving credit account.Inputs: account balanceProcess: Computes interestinterest according to:1.5% on 1st $10001.0% on all over $1000adds this to account balance get total due.Computes minimum payment according to:if amount due < $10,minimum payment is total dueelseminimum payment is 10% of total dueoutputs: Interest due, total amount due, minimum paymentThe class is the account.the public interface has functions:constructorsdefault constructorconstructor with parameter balance,computes interest, total due, minimum payinterestDue() reports interesttotalDue() reports total amount dueminPayDue() reports minimum payment dueprivate databalancetotal dueinterest dueminimum paymentClass-object Implementation://file: //Interest//class-object solution//Purpose: Compute interest due, total amount due, and minimum payment //for a revolving credit account.////Inputs: account balance////Process: Computes interest// interest according to:// 1.5% on 1st $1000 of balance// 1.0% on all over $1000 of balance// adds this to account balance get total due.// Computes minimum payment according to:// if amount due < $10,// minimum payment is total due// else// minimum payment is 10% of total due////outputs: Interest due, total amount due, minimum payment#include <iostream>using namespace std;const double INTEREST_RATE1 = 0.015;const double INTEREST_RATE2 = 0.01;const double MINPAY_FRACTION = 0.10;class CreditAccount{public:CreditAccount(); // sets everything to 0CreditAccount( double balance );// computes everything needed double interestDue();double totalDue();double minPayDue();private:double balance;double interestDue;double totalDue;double minPay;};double CreditAccount::interestDue(){return interestDue;}double CreditAccount::totalDue(){return totalDue;}double CreditAccount::minPayDue(){return minPay;}CreditAccount::CreditAccount():balance(0),totalDue(0), interestDue(0), minPay(0){//Body deliberately left empty.//This is a C++ idiom. See this IRM Chapter 10.// This is covered in Appendix 7 of the text}CreditAccount::CreditAccount( double balance ){if (balance <= 1000 )interestDue = balance*INTEREST_RATE1;else if ( balance > 1000 )interestDue = 1000*INTEREST_RATE1 + (balance - 1000)*INTEREST_RATE2; totalDue = balance + interestDue;if (totalDue <= 10 )minPay = totalDue;elseminPay = totalDue * MINPAY_FRACTION;}int main(){cout.setf(ios::showpoint);cout.setf(ios::fixed);cout.precision(2);char ans;double balance;do{cout << "Enter the account balance, please: " ;cin >> balance;CreditAccount account( balance );cout << "Interest due: " << account.interestDue() << endl<< "Total due: " << account.totalDue() << endl<< "Minimum Payment: " << account.minPayDue() << endl;cout << "Y/y repeats. any other quits" << endl;cin >> ans;}while('y' ==ans || 'Y' == ans );}A typical run for the class/object solution follows:Enter the account balance, please: 9.00Interest due: 0.14Total due: 9.13Minimum Payment: 9.13Y/y repeats. any other quitsyEnter the account balance, please: 9.85Interest due: 0.15Total due: 10.00Minimum Payment: 10.00Y/y repeats. any other quitsyEnter the account balance, please: 985.22Interest due: 14.78Total due: 1000.00Minimum Payment: 100.00Y/y repeats. any other quitsyEnter the account balance, please: 1000Interest due: 15.00Total due: 1015.00Minimum Payment: 101.50Y/y repeats. any other quitsyEnter the account balance, please: 2000Interest due: 25.00Total due: 2025.00Minimum Payment: 202.50Y/y repeats. any other quitsq2. Credit Account problem -- Conventional solutionCompute interest due, total amount due, and minimum payment for a revolving credit account. Inputs: account balanceProcess: Computes interestinterest according to:1.5% on 1st $10001.0% on all over $1000adds this to account balance get total due.Computes minimum payment according to:if amount due < $10,minimum payment is total dueelseminimum payment is 10% of total dueoutputs: Interest due, total amount due, minimum paymentdatabalancetotal dueinterest dueminimum payment//file: //conventional solution////Purpose: Compute interest due, total amount due, and minimum payment //for a revolving credit account.////Inputs: account balance////Process: Computes interest// interest according to:// 1.5% on 1st $1000 of balance// 1.0% on all over $1000 of balance// adds this to account balance get total due.// Computes minimum payment according to:// if amount due < $10,// minimum payment is total due// else// minimum payment is 10% of total due////Outputs: Interest due, total amount due, minimum payment#include <iostream>using namespace std;const double INTEREST_RATE1 = 0.015;const double INTEREST_RATE2 = 0.01;const double MINPAY_FRACTION = 0.10;double interestDue(double balance){if (balance <= 1000 )return balance*INTEREST_RATE1;return 1000*INTEREST_RATE1 + (balance - 1000)*INTEREST_RATE2; }double minPay(double totalDue){if (totalDue <= 10 )return totalDue;return totalDue * MINPAY_FRACTION;}int main(){double balance;double interestDue;double totalDue;double minPay;cout.setf(ios::showpoint);cout.setf(ios::fixed);cout.precision(2);char ans;do{cout << "Enter the account balance, please: " ;cin >> balance;interestDue = interestDue(balance);totalDue = balance + interestDue;minPay = minPay(totalDue);cout << "Interest due: " << interestDue << endl<< "Total due: " << totalDue << endl<< "Minimum Payment: " << minPay << endl;cout << "Y/y repeats. any other quits" << endl;cin >> ans;}while ( 'y' ==ans || 'Y' == ans );}A typical run for the conventional solution does not differ significantly from the …class‟ based solution.3. Astrology Class/Object solution.Notes:I have not done a conventional solution. All the bits and pieces necessary to do a conventional solution are present here. I also have not done the enhancements suggested. I have, however, included comments that suggest how to carry out these enhancements.I have used slightly modified new_line and display_line code from the text. Encourage students not to reinvent the wheel, that is, to use bits and pieces code from the book and other sources as long as copyrights are not violated.I used a library book on astrology for my reference. A newspaper works as well.Planning:Input: user's birthday. Month 1-12, day 1-31Process: table lookup of signs and horoscopes, with repeat at user's optionOutput: Sign of the Zodiac and horoscope for that birthday.Hint: user a newspaper horoscope for names, dates and ahoroscope for each sign.Enhancement: If birthday is within 2 days of the adjacentsign, announce that the birthdate is on a "cusp" and outputthe horoscope for the adjacent sign also.Comments and suggestions. Program will have a long multiwaybranch. Store the horoscopes in a file.Ask your instructor for any special instructions, such as file name orlocation if this is a class assignment.Planning for the solution:What are the object and classes?The Astrological Chart would be the class if we were doing a full chart. We are only selecting the Sun Sign, but we still let Astro be the class.Zodiac Sign names and dates:Aries March 21 - April 19Tarus April 20 - May 20Gemini May 21 - June 21Cancer June 22 - July 22Leo July 23 - August 22Virgo August 23 - September 22Libra September 23 - October 22Scorpio October 23 - November 21Sagittarius November 22 - December 21Capricorn December 21 - January 19Aquarius January 19 - February 18Pices February 19 - March 20Horoscope file structure.The initial <cr> is necessary given this code to prevent output from running on from the first horoscope. (We did not make use of the sign number.)<cr>sign numberhoroscope#sign numberhoroscope#and so on.Pseudocode for the class and what member functions do...class Astro{public:constructorsAstro();Astro( Date birthday);looks up and sets the sign number,Enhancement:sets iscusp to -1 if birthday is within 2 daysbefore the adjacent sign, to -1 if within 2 daysafter adjacent sign and 0 if neither.member functionsvoid horoscope ();Enhancement:if iscusp == -1, report horoscope before thecurrent one and the current one.else if iscusp == 1, report the current horoscopeand the one following.else // iscusp == 0, do the default action:Unenhanced action:Dump the horoscopes from file up to the current one.Display current horoscope.How? # is sentinel for end of a horoscope. Dump horoscopesthrough (signNumber -1) # symbols, using utilityfunctions. Display through next # using utilityfunctions.private:Day birthday;int signNumber;void newHoroscope(istream & inStream);// display inStream to next # and discard the #void displayHoroscope( istream& sourceFile);// read and ignore inStream through the next #//Enhancement:// int isCusp(};Planning done, now to the coding. The contents of “horoscope.dat” are listed with the …typical run‟ at the end of the following code.// Program: file: // Requires file "horoscope.dat" having structure// lines of text// #// lines of text// #// ...// lines of text// ##include <fstream> //for stream io#include <stdlib> //for exit()using namespace std;// an enum could have certainly been used hereconst int aries = 1;const int taurus = 2;const int gemini = 3;const int cancer = 4;const int leo = 5;const int virgo = 6;const int libra = 7;const int scorpio = 8;const int Sagittarius = 9;const int capricorn = 10;const int aquarius = 11;const int pisces = 12;//const makes certain no error that changes these constants is made.struct month //no checking is done... Let the user be warned!{int day; // 1..28, or 29 or 30 or 31, depending on month.int month; // 1..12};class Astro{public:Astro();Astro( month birthday);// looks up and sets the sign number//Enhancement: sets iscusp to -1 if birthday is within 2 days // before the adjacent sign, to -1 if within 2 days// after adjacent sign and 0 if neither.void horoscope ();//Enhancement: if iscusp == -1,// dump (signNumber - 2) horoscopes// else if iscusp == 1// dump (signNumber - 1) horoscopes// display next two horoscopes.// return;// unenhanced action: if we get here, iscusp == 0 so we// dump (signNumber - 1) horoscopes,// display next horoscope.private:month birthday;int signNumber;void newHoroscope(istream & inStream);void displayHoroscope( istream& sourceFile);//Enhancement:// int isCusp;};// dumps all from file through the next #void Astro::newHoroscope(istream & inStream){char symbol;do{inStream.get(symbol);} while(symbol != '#' );}//displays all from file through the next #void Astro::displayHoroscope( istream& sourceFile){char next;sourceFile.get(next);while ( '#' != next ){cout << next;sourceFile.get(next);}}void Astro::horoscope(){ifstream infile;infile.open( "horoscope.dat");int c;// cusp == 0 case: dump signNumber - 1 horoscopes.for ( int i = 1; i < signNumber; i++)newHoroscope( infile );displayHoroscope( infile );cout << endl;//Enhancement, change from //cusp==0 case://so that// if (cusp == -1)// dump thru (signNumber - 2) horoscopes// else if(cusp == 1 )// dump thru (signNumber - 1) hororscopes// from this position,// display two horoscopes// return// this is the cusp = 0 case, as above.}Astro::Astro() // I prefer to use the class initializer list { // notation. This follows the textsignNumber = 0;// isCusp = 0; // for one of the enhancements I did not do }Astro::Astro( month birthday)//int signNumber( month birthday ) // to test this turkey// looks up and sets the sign number,{switch( birthday.month ){case 1:if (birthday.day <= 19) signNumber = capricorn;else signNumber = aquarius;// enhancement code will look like this in all the cases:// if ( 17 <= birthday.day && birthday.day < 19 )cusp = -1;// else if ( 19 < birthday.day && birthday.day <= 21 )cusp = -1; // else cusp = 0;//break;case 2:if ( birthday.day <= 18 ) signNumber = aquarius;else signNumber = pisces;break;case 3:if ( birthday.day <=20 ) signNumber = pisces;else signNumber = aries;break;case 4:if ( birthday.day <= 19 ) signNumber = aries;else signNumber = taurus;break;case 5:if (birthday.day <= 20 ) signNumber = taurus;else signNumber = gemini;break;case 6:if (birthday.day <= 21 ) signNumber = gemini;else signNumber = cancer;break;case 7:if (birthday.day <= 22 ) signNumber = cancer;else signNumber = leo;break;case 8:if (birthday.day <= 22 ) signNumber = leo;else signNumber = virgo;break;case 9:if (birthday.day <= 22 ) signNumber = virgo;else signNumber = libra;break;case 10:if (birthday.day <= 22 ) signNumber = libra;else signNumber = scorpio;break;case 11:if (birthday.day <= 21 ) signNumber = scorpio;else signNumber = sagittarius;break;case 12:if (birthday.day <= 21 ) signNumber = sagittarius;else signNumber = capricorn;break;default: cout << "no such month as " << birthday.month<< " Aborting " << endl;exit(1);break;}}int main(){month birthday;cout << "Any non-digit in the month field will terminate the program." << endl;cout << "Enter birthday in numeric form: month day, as 12 5 : "<< endl;cin >> birthday.month >> birthday.day;do{cout << birthday.month << " " << birthday.day;Astro user(birthday);user.horoscope();cout << "Enter birthday in numeric form: month day, as 12 5: " << endl; cin >> birthday.month >> birthday.day;} while ( cin );}Test Data and Runs.Space restrictions prohibit including a complete horoscope here for each Sun Sign. I have created an abbreviated test file for Horoscopes. (The carriage return at the start of the file is necessary to obtain acarriage return before the Aries horoscope.)$cat horoscope.dat1 Aries#2 Taurus#3 Gemini#4 Cancer#5 Leo#6 Virgo#7 Libra#8 Scorpio#9 Sagittarius#10 Capricorn#11 Aquarius#12 Pisces#A shortened typical run with the test data file following:a.out < data | lessTest data: first entry is the month, second is the day:cat data1 191 201 212 182 19several dates omitted10 2411 2011 2111 2212 2112 2212 23Output from this run:Enter birthday in numeric form: day month, as 12 5:1 1910 CapricornEnter birthday in numeric form: day month, as 12 5:1 2011 AquariusEnter birthday in numeric form: day month, as 12 5:1 2111 AquariusSeveral lines of output have been deleted.Enter birthday in numeric form: day month, as 12 5:12 219 SagittariusEnter birthday in numeric form: day month, as 12 5:12 2210 CapricornEnter birthday in numeric form: day month, as 12 5:12 2310 CapricornEnter birthday in numeric form: day month, as 12 5:4. Modify Horoscope// File: ch3.4.cpp// Modify File: ch3.3.cpp//// Modify Project 3 to request the user's birthday then// to display the three most compatible astrological signs// (having the same Element)//// Elements are Earth, Air, Fire, and Water,// Fire signs are Aries, Leo, Sagittarius// Earth signs are Taurus, Virgo, Capricorn// Air signs are Gemini, Libra, Aquarius// Water signs are Cancer, Scorpio, Pisces//// Known Bugs:// Day number is only partially verified. Program aborts if the// day number > 31. No further checking is done for day input errors // such as Feb 29 on non-leap-years or April 31.// Enhancements suggested from #3 are not implemented. Hints// on how to do the enhancements are given in strategic places// in comments.// Program: file: // Requires file "horoscope.dat" having structure// lines of text// #// lines of text。
C++面向对象程序设计课后答案(1-4章)第一章:面向对象程序设计概述[1_1]什么是面向对象程序设计?面向对象程序设计是一种新型的程序设计范型。
这种范型的主要特征是:程序=对象+消息。
面向对象程序的基本元素是对象,面向对象程序的主要结构特点是:第一:程序一般由类的定义和类的使用两部分组成,在主程序中定义各对象并规定它们之间传递消息的规律。
第二:程序中的一切操作都是通过向对象发送消息来实现的,对象接受到消息后,启动有关方法完成相应的操作。
面向对象程序设计方法模拟人类习惯的解题方法,代表了计算机程序设计新颖的思维方式。
这种方法的提出是软件开发方法的一场革命,是目前解决软件开发面临困难的最有希望、最有前途的方法之一。
[1_2]什么是类?什么是对象?对象与类的关系是什么?在面向对象程序设计中,对象是描述其属性的数据以及对这些数据施加的一组操作封装在一起构成的统一体。
对象可以认为是:数据+操作在面向对象程序设计中,类就是具有相同的数据和相同的操作的一组对象的集合,也就是说,类是对具有相同数据结构和相同操作的一类对象的描述。
类和对象之间的关系是抽象和具体的关系。
类是多个对象进行综合抽象的结果,一个对象是类的一个实例。
在面向对象程序设计中,总是先声明类,再由类生成对象。
类是建立对象的“摸板”,按照这个摸板所建立的一个个具体的对象,就是类的实际例子,通常称为实例。
[1_3]现实世界中的对象有哪些特征?请举例说明。
对象是现实世界中的一个实体,其具有以下一些特征:(1)每一个对象必须有一个名字以区别于其他对象。
(2)需要用属性来描述它的某些特性。
(3)有一组操作,每一个操作决定了对象的一种行为。
(4)对象的操作可以分为两类:一类是自身所承受的操作,一类是施加于其他对象的操作。
例如:雇员刘名是一个对象对象名:刘名对象的属性:年龄:36 生日:1966.10.1 工资:2000 部门:人事部对象的操作:吃饭开车[1_4]什么是消息?消息具有什么性质?在面向对象程序设计中,一个对象向另一个对象发出的请求被称为“消息”。
1.Windows 编程中窗口的含义是什么?Windows应用程序基本的操作单元,系统管理应用程序的基本单位,应用程序与用户之间交互的接口环境2.事件驱动的特点是什么?Windows程序设计是针对事件或消息的处理进行。
Windows程序的执行顺序取决于事件发生的顺序,程序的执行顺序是由顺序产生的消息驱动的,但是消息的产生往往并不要求有次序之分。
事件驱动编程方法对于编写交互式程序很有用处,它避免了死板的操作模式。
4.句柄的作用是什么?请举例说明句柄是整个windows编程的基础,是一个4字节长的数值,用于标识应用程序中不同的对象和同类对象中不同的实例。
应用程序通过句柄访问相应的对象信息。
Typedef struct tagPOINT{LONG X; LONG Y;}POINT5.一个windows应用程序的最基本构成有哪些部分(5)部分组成,1).C语言源程序文件c或者cpp 2).头文件h3).模块定义文件def 4).资源描述文件rc 5).项目文件vcproj6.应用windows API函数编程有什么特点1)为应用程序提供Windows系统特殊函数及数据结构2)Win应用程序可以利用标准大量API函数调用系统功能3)是Win系统与Win应用程序间的标准程序接口。
功能:窗口管理函数:实现窗口的创建、移动和修改功能,系统服务函数:实现与操作系统有关的多种功能,图形设备(GDI)函数:实现与设备无关的图形操作功能7.Windows编程中有哪些常用的数据类型LONG 32 位有符号整数,DWORD 32 位无符号整数,UINT 32 位无符号整数,BOOL布尔值,LPTSTR 指向字符串的32 位指针,LPCTSTR 指向字符串常量的32 位指针,LPSTR 指向字符串的32 位指针,LPCSTR 指向字符串常量的32 位指针。
9.简述winmain函数和窗口函数的结构及功能三个基本的组成部分:函数说明、初始化和消息循环,功能:注册窗口类,建立窗口及执行必要的初始化,进入消息循环,根据接受的消息调用相应的处理过程,当消息循环检索到WM_QUIT时终止程序运行。
第3章习题解答1.如何定义方法?在面向对象程序设计中方法有什么作用?答:方法的定义包括方法名、方法形参、方法的返回值类型和方法体四部分,方法只能在类中定义。
方法是对象的动态特征的描述,对象通过方法操作属性,进而改变对象的状态,完成程序所预期的功能。
2.定义一个Dog类,有名字、颜色、年龄等属性,定义构造方法用来初始化类的这些属性,定义方法输出Dog的信息。
编写应用程序使用Dog。
答:public class Dog{private String name;private String color;private String age;Dog(String n,String c,String a){name = n; color = c; age = a;}public String toString() {return name + "," + color + "," + age;}public static void main(String args[]) {Dog dog = new Dog("小白", "白色", "2岁");System.out.println(dog.toString());}}3.什么是访问控制修饰符?修饰符有哪些种类?它们各有何作用?答:访问控制修饰符是对类、属性和方法的访问权限的一种限制,不同的修饰符决定了不同的访问权限。
访问控制修饰符有3个:private、protected、public,另外还有一种默认访问权限。
各个修饰符的作用如下表所示:B:包中的类C:所有子类D:本类A:所有类:所有类4.阅读程序,写出程序的输出结果class A{private int privateVar;A(int _privateVar){privateVar=_privateVar;}boolean isEqualTo(A anotherA){if(this.privateVar == anotherA.privateVar)return true;elsereturn false;}}public class B{public static void main(String args[]){A a = new A(1);A b = new A(2);System.out.println(a.isEqualTo(b));}}程序的输出结果为:false5.阅读程序,写出程序的输出结果public class Test {public static void main(String[] args) {int x;int a[] = { 0, 0, 0, 0, 0, 0 };calculate(a, a[5]);System.out.println("the value of a[0] is " + a[0]);System.out.println("the value is a[5] is " + a[5]);}static int calculate(int x[], int y) {for (int i = 1; i < x.length; i++)if (y < x.length)x[i] = x[i - 1] + 1;return x[0];}}程序的输出结果为:the value of a[0] is 0the value is a[5] is 56.阅读程序,写出程序的输出结果public class Test {public static void main(String[] args) {String str1 = new String("Java");String str2 = new String("Java");System.out.println(str1 == str2);}}程序的输出结果为:false7.阅读下列程序,程序中已经指明错误位置,请说出错误原因。