[VIP专享]面向对象程序设计第二章课后答案
面向对象程序设计课后答案(完整版)

面向对象程序设计课后答案(完整版)第二章2-4#includeusing namespace std;Add(int a,int b);int main(){int x,y,sum;cout>x>>y;sum = add(x,y);cout >*p;p++;}p = p-20;for( i=0;i0) countp++;if(*p>age ;try{checkagescore(name,age);}catch( string){cout<<"exception :name is exit"<<endl;continue;}catch(int){cout<<"exception :age is not proper"<<endl;continue;}cout<<"name:"<<name<<" age :"< }return 0;}第三章3-1(1)A (2)C (3)B (4)C (5)C(6)B (7)B (8)C (9)C3-7(1)main()函数中p1.age = 30;语句是错误的。
age 是类的私有成员(2)构造函数应当给常数据成员和引用成员初始化,将构造函数改为:A(int a1,int b1):a(a1),b(b1){}或A(int a1 ):a(a1),b(a){}再将main中的A a(1,2); 改为A a(1);(3)(1)在Test 类中添加语句:void print();void Print(){cout<<x<<"-"<<y<<"="<<x-y<<endl;}改为void Test::Print(){cout<<x<<"-"<<y<<"="<<x-y<<endl;}main函数中Init(38,15);改为:A.Init(38,15);Print();改为:A.Print();3-8(1)Constructing AConstructing BDestructing BDestructing A(2)double a,double bpoint & pp.x3-9class box{int len1,len2,len3;public:box(int l1,int l2,int l3){len1 = l1;len2 = l2; len3 = l3;} long volumn(){return len1*len2*len3;}};3-10class Test{int m1,m2;public:void Init(int a,int b){m1 = a;m2 = b;}void Pring(){cout<<m1<<" "<<m2<<endl;}};3-11略3-12}第四章4-6(1)D (2)D (3)D (4)D (5)B(6)D4-7(1)static int count = 0;这样初始化静态成员值是不对的将其改为static int count;在类外,main函数前加int Sample::count = 0;(2)#include//#includeusing namespace std;class Ctest{private:int x; const int y1;public:const int y2;Ctest(int i1,int i2):y1(i1),y2(i2) {y1 =10;//y1 为常量不能赋值x = y1;}int readme() const;};int Ctest::readme ()const{int i;i = x;x++; //常函数内不能改变成员值return x;}int main(){Ctest c(2,8);int i = c.y2;c.y2 = i;//y2为常量,不能改值i = c.y1;//y1私有,类外不能访问return 0;}将出错语句全部注释4-8(1)题中印刷错误,将class C构造函数改为: C(){cout<<"constructor C:";}运行结果为:constructor Aconstructor Bconstructor C(2)40(3)3434-9#include#includeclass Date{int year;int month;int day;public:Date(int y,int m,int d){year=y;month=m;day=d;}void disp(){cout<<year<<" "<<month<<" "<<day<<endl;}friend int count_day(Date &d,int k);friend int l(int year);friend int h(Date &d1,Date &d2);};int count_day(Date &d,int k){static int day_tab[2][12]={{31,28,31,30,31,30,31,31,30,31,30,3 1},{31,29,31,30,31,30,31,31,30,31,30,31}};// 使用二维数组存放各月天数,第一行对应非闰年,第二行对应闰年int j,i,s;if(l(d.year))j=1;//闰年,取1else j=0;//非闰年,取0if(k)//K非0时{s=d.day;for(i=1;i<d.month;i++)//d.month为输入的月份s+=day_tab[j][i-1];}else//K为0时{s=day_tab[j][d.month]-d.day;for(i=d.month+1; i<=12; i++)s+=day_tab[j][i-1];}return s;//S为相差的天数}int l(int year){if(year%4==0&&year%100!=0||year%400==0) // 是闰年return 1;else // 不是闰年return 0;}int h(Date &d1,Date &d2){int days,day1,day2,y;if(d1.year<d2.year)//第一个日期年份小于第二个日期年份{days=count_day(d1,0);for(y=d1.year+1;y<d2.year;y++)if(l(y))//闰年。
[VIP专享]面向对象程序设计第二章课后答案
![[VIP专享]面向对象程序设计第二章课后答案](https://img.taocdn.com/s3/m/6e7a75a8fab069dc50220163.png)
1.什么是命名空间,如何访问命名空间的成员?【解答】为了解决不同文件中同名变量的问题,C++标准中引入命名空间的概念。
命名空间(namespace)是一种特殊的作用域,命名空间可以由程序员自己来创建,可以将不同的标识符集合在一个命名作用域内,这些标识符可以类、对象、函数、变量、结构体、模板以及其他命名空间等。
在作用域范围内使用命名空间就可以访问命名空间定义的标识符。
有3种访问方法:(1)直接指定标识符,访问方式为:命名空间标识符名∷成员名。
(2)使用using namespace命令(3)使用using关键词声明2.什么是内联函数,它有什么特点?哪些函数不能定义为内联函数?【解答】用inline关键字声明或定义的函数称为内联函数。
C++中对于功能简单、规模小、使用频繁的函数,可以将其设置为内联函数。
内联函数(inline function)的定义和普通函数相同,但C++对它们的处理方式不一样。
在编译时,C++将用内联函数程序代码替换对它每次的调用。
这样,内联函数没有函数调用的开销,即节省参数传递、控制转移的开销,从而提高了程序运行时的效率。
但是,由于每次调用内联函数时,需要将这个内联函数的所有代码复制到调用函数中,所以会增加程序的代码量,占用更多的存储空间,增大了系统空间方面的开销。
因此,内联函数是一种空间换时间的方案。
函数体内有循环语句和switch语句,递归调用的函数不能定义为内联函数。
3.什么是函数重载?在函数调用时,C++是如何匹配重载函数的?【解答】函数重载是指两个或两个以上的函数具有相同的函数名,但参数类型不一致或参数个数不同。
编译时编译器将根据实参和形参的类型及个数进行相应地匹配,自动确定调用哪一个函数。
使得重载的函数虽然函数名相同,但功能却不完全相同。
在函数调用时,C++是匹配重载函数规则如下:首先寻找一个精确匹配,如果能找到,调用该函数;其次进行提升匹配,通过内部类型转换(窄类型到宽类型的转换)寻求一个匹配,如char到int、short到int等,如果能找到,调用该函数;最后通过强制类型转换寻求一个匹配,如果能找到,调用该函数。
C++面向对象程序设计教程课后习题答案

tem = a[i]; a[i] = a[j]; a[j] = tem;
}
}
……
整理课件
9
*5.编一个程序,用同一个函数名对n个数据进行从小到大排序,数据类型可
以是整型、单精度实型、双精度实型,用重载函数实现。
参考程序:
……
void Sort(float a[], int n)
// 对a[0]...a[n-1]进行排序
// 定义变量
for (i = 0; i < n- 1; i++)
for (j = i + 1; j < n; j++)
if (a[i] > a[j])
{
// a[i]比a[j]更大
tem = a[i]; a[i] = a[j]; a[j] = tem;
}
}
……
整理课件
11
*5.编一个程序,用同一个函数名对n个数据进行从小到大排序,数据类型可
double c[] = {1.2, 3.1, 2.6, 5.8, 6.8, 9.8, 0.8, 6.2};// 定义c
int i, n = 8;
// 定义变量
Sort(a, n); cout << "a:"; for (i = 0; i < n; i++)
cout << a[i] << " "; cout << endl;
Fun(a);
// 调用Fun()
return 0;
// 返回值0, 返回操作系统
}
该程序执行后输出的结果是 。
A)1
java面向对象程序设计第二版课后答案.doc

java 面向对象程序设计第二版课后答案【篇一:java 面向对象程序设计课后答案】s=txt>java 面向对象程序设计清华大学出版社(编著耿祥义张跃平)习题解答建议使用文档结构图(选择word 菜单→视图→文档结构图)习题11.james gosling、、、、2.(1)使用一个文本编辑器编写源文件。
(2)使用java 编译器(javac.exe )编译java 源程序,得到字节码文件。
(3)使用java 解释器(java.exe )运行java 程序3.java 的源文件是由若干个书写形式互相独立的类组成的。
应用程序中可以没有public 类,若有的话至多可以有一个public 类。
4.系统环境path d\jdk\bin;系统环境classpath d\jdk\jre\lib\rt.jar;.;5. b6.java 源文件的扩展名是.java 。
java 字节码的扩展名是.class 。
7. d8.(1)speak.java(2)生成两个字节码文件,这些字节码文件的名字speak.class 和xiti8.class ava xiti8(4)执行java speak 的错误提示exception in thread main ng.nosuchmethoderror: main 执行java xiti8 得到的错误提示exception in thread main ng.noclassdeffounderror: xiti8 (wrong name: xiti8) 执行java xiti8.class 得到的错误提示exception in thread main ng.noclassdeffounderror:xiti8/class 执行java xiti8 得到的输出结果im glad to meet you9.属于操作题,解答略。
习题21. d2.【代码1】【代码2】错误//【代码3】更正为float z=6.89f; 3.float 型常量后面必须要有后缀“f或”“f。
面向对象的C++程序设计 第六版 课后习题答案第二章

Chapter 2C++ Basics1. Solutions to the Programming Projects:1. Metric - English units ConversionA metric ton is 35,273.92 ounces. Write a C++ program to read the weight of a box of cereal in ounces then output this weight in metric tons, along with the number of boxes to yield a metric ton of cereal.Design: To convert 14 ounces (of cereal) to metric tons, we use the 'ratio of units' to tell us whether to divide or multiply:1 metric tons14 ounces * * = 0.000397 metric tons35,273 ouncesThe use of units will simplify the determination of whether to divide or to multiply in making a conversion. Notice that ounces/ounce becomes unit-less, so that we are left with metric ton units. The number of ounces will be very, very much larger than the number of metric tons. It is then reasonable to divide the number of ounces by the number of ounces in a metric ton to get the number of metric tons.Now let metricTonsPerBox be the weight of the cereal box in metric tons. Let ouncesPerBox the be the weight of the cereal box in ounces. Then in C++ the formula becomes:const double ouncesPerMetric_ton = 35272.92; metricTonsPerBox = ouncesPerBox / ouncesPerMetricTon;This is metric tons PER BOX, whence the number of BOX(es) PER metric ton should be the reciprocal:boxesPerMetricTon = 1 / metricTonsPerBox;Once this analysis is made, the code proceeds quickly://Purpose: To convert cereal box weight from ounces to // metric tons to compute number of boxes to make up a // metric ton of cereal.#include <iostream>using namespace std;const double ouncesPerMetricTon = 35272.92;int main(){double ouncesPerBox, metricTonsPerbox,boxesPerMetricTon;char ans = 'y';while( 'y' == ans || 'Y' == ans ){cout << “enter the weight in ounces of your”<< “favorite cereal:” <<end l;cin >> ouncesPerBox;metricTonsPerbox =ouncesPerBox / ouncesPerMetricTon;boxesPerMetricTon = 1 / metricTonsPerbox;cout << "metric tons per box = "<< metricTonsPerbox << endl;cout << "boxes to yield a metric ton = "<< boxesPerMetricTon << endl;cout << " Y or y continues, any other character ”<< “terminates." << endl;cin >> ans;}return 0;}A sample run follows:enter the weight in ounces of your favorite cereal:14metric tons per box = 0.000396905boxes to yield a metric ton = 2519.49Y or y continues, any other characters terminates.yenter the weight in ounces of your favorite cereal:20metric tons per box = 0.000567007boxes to yield a metric ton = 1763.65Y or y continues, any other characters terminates.n2. Lethal DoseCertain artificial sweeteners are poisonous at some dosage level. It is desired to know how much soda a dieter can drink without dying. The problem statement gives no information about how to scale the amount of toxicity from the dimensions of the experimental mouse to the dimensions of the dieter. Hence the student must supply this necessary assumption as basis for the calculation.This solution supposes the lethal dose is directly proportional to the weight of the subject, henceweightOfDieterlethalDoseDieter = lethalDoseMouse *weightOfMouseThis program accepts weight of a lethal dose for a mouse, the weight of the mouse, and the weight of the dieter, and calculates the amount of sweetener that will just kill the dieter, based on the lethal dose for a mouse in the lab. If the student has problems with grams and pounds, a pound is 454 grams.It is interesting that the result probably wanted is a safe number of cans, while all the data can provide is the minimum lethal number! Some students will probably realize this, but my experience is that most will not. I just weighed a can of diet pop and subtracted the weight of an empty can. The result is about 350 grams. The label claims 355 ml, which weighs very nearly 355 grams. To get the lethal number of cans from the number of grams of sweetener, you need the number of grams ofsweetener in a can of pop, and the concentration of sweetener, which the problem assumes 0.1% , that is a conversion factor of 0.001.gramsSweetenerPerCan = 350 * 0.001 = 0.35 grams/cancans = lethalDoseDieter / (0.35 grams / can)////Input: lethal dose of sweetener for a lab mouse, weights// of mouse and dieter, and concentration of sweetener in a // soda.//Output: lethal dose of soda in number of cans.//Assumption: lethal dose proportional to weight of subject// Concentration of sweetener in the soda is 1/10 percent #include <iostream>using namespace std;const double concentration = .001; // 1/10 of 1 percentconst double canWeight = 350;const double gramsSweetnerPerCan = canWeight concentration; //units of grams/canint main(){double lethalDoseMouse, lethalDoseDieter,weightMouse, weightDieter; //units: gramsdouble cans;char ans;do{cout << "Enter the weight of the mouse in grams"<< endl;cin >> weightMouse;cout << "Enter the lethal dose for the mouse in“<< ”grams " << endl;cin >> lethalDoseMouse;cout << "Enter the desired weight of the dieter in”<<“ grams " << endl;cin >> weightDieter;lethalDoseDieter =lethalDoseMouse weightDieter/weightMouse;cout << "For these parameters:\nmouse weight: "<< weightMouse<< " grams " << endl<< "lethal dose for the mouse: "<< lethalDoseMouse<< "grams" << endl<< "Dieter weight: " << weightDieter<< " grams " << endl<< "The lethal dose in grams of sweetener is: "<< lethalDoseDieter << endl;cans = lethalDoseDieter / gramsSweetnerPerCan;cout << "Lethal number of cans of pop: "<< cans << endl;cout << "Y or y continues, any other character quits"<< endl;cin >> ans;} while ( 'y' == ans || 'Y' == ans );return 0;}A typical run follows:17:23:09:~/AW$ a.outEnter the weight of the mouse in grams15Enter the lethal dose for the mouse in grams100Enter the desired weight of the dieter, in grams 45400For these parameters:mouse weight: 15 gramslethal dose for the mouse: 100 gramsDieter weight: 45400 gramsThe lethal dose in grams of sweetener is: 302667 Lethal number of cans of pop: 864762Y or y continues, any other character quitsyEnter the weight of the mouse in grams30Enter the lethal dose for the mouse in grams100Enter the desired weight of the dieter, in grams 45400For these parameters:mouse weight: 30 gramslethal dose for the mouse: 100 gramsDieter weight: 45400 gramsThe lethal dose in grams of sweetener is: 151333 Lethal number of cans of pop: 432381Y or y continues, any other character quitsq17:23:56:~/AW$3. Pay IncreaseThe workers have won a 7.6% pay increase, effective 6 months retroactively. This program is to accept the previous annual salary, then outputs the retroactive pay due the employee, the new annual salary, and the new monthly salary. Allow user to repeat as desired. The appropriate formulae are:const double INCREASE = 0.076;newSalary = salary * (1 + INCREASE);monthly = salary / 12;retroactive = (salary – oldSalary)/2;The code follows:////Given 6 mos retroactive 7.6% pay increase,//input salary//Output new annual and monthly salaries, retroactive pay#include <iostream>using namespace std;const double INCREASE = 0.076;int main(){double oldSalary, salary, monthly, retroactive;char ans;cout << "Enter current annual salary." << endl<< "I'll return new annual salary, monthly ”<< “salary, and retroactive pay." << endl;cin >> oldSalary;//old annual salarysalary = oldSalary*(1+INCREASE);//new annual salarymonthly = salary/12;retroactive = (salary – oldSalary)/2;cout << "new annual salary " << salary << endl;cout << "new monthly salary " << monthly << endl;cout << "retroactive salary due: "<< retroactive << endl;return 0;}17:50:12:~/AW$ a.outEnter current annual salary.100000I'll return new annual salary, monthly salary, andretroactive pay.new annual salary 107600new monthly salary 8966.67retroactive salary due: 38004. Retroactive Salary// File: Ch2.4.cpp// Modify program from Problem #3 so that it calculatesretroactive// salary for a worker for a number of months entered by the user. //Given a 7.6% pay increase,//input salary//input number of months to compute retroactive salary//Output new annual and monthly salaries, retroactive pay#include <iostream>const double INCREASE = 0.076;int main(){using std::cout;using std::cin;using std::endl;double oldSalary, salary, monthly, oldMonthly, retroactive;int numberOfMonths; // number of months to pay retroactiveincreasechar ans;cout << "Enter current annual salary and a number of months\n"<< "for which you wish to compute retroactive pay.\n"<< "I'll return new annual salary, monthly "<< "salary, and retroactive pay." << endl;cin >> oldSalary;//old annual salarycin >> numberOfMonths;salary = oldSalary * (1+INCREASE); //new annual salaryoldMonthly = oldSalary/12;monthly = salary/12;retroactive = (monthly - oldMonthly) * numberOfMonths;// retroactive = (salary - oldSalary)/2; // six monthsretroactive pay increase.cout << "new annual salary " << salary << endl;cout << "new monthly salary " << monthly << endl;cout << "retroactive salary due: "<< retroactive << endl;return 0;}/*Typical runEnter current annual salary and a number of monthsfor which you wish to compute retroactive pay.I'll return new annual salary, monthly salary, and retroactive pay. 120009new annual salary 12912new monthly salary 1076retroactive salary due: 684Press any key to continue*/5. No solution provided.6. No solution provided.7. PayrollThis problem involves payroll and uses the selection construct. A possible restatement: An hourly employee's regular payRate is $16.78/hour for hoursWorked <= 40 hours. If hoursWorked > 40 hours, then (hoursWorked -40) is paid at an overtime premium rate of 1.5 * payRate. FICA (social security) tax is 6% and Federal income tax is 14%. Union dues of$10/week are withheld. If there are 3 or more covered dependents, $15 more is withheld for dependent health insurance.a) Write a program that, on a weekly basis, accepts hours worked then outputs gross pay, each withholding amount, and net (take-home) pay.b) Add 'repeat at user discretion' feature.I was unpleasantly surprised to find that with early GNU g++ , you cannot use a leading 0 (such as an SSN 034 56 7891) in a sequence of integer inputs. The gnu iostreams library took the integer to be zero and went directly to the next input! You either have to either use an array of char, or 9 char variables to avoid this restriction.Otherwise, the code is fairly straight forward.//file //pay roll problem://Inputs: hoursWorked, number of dependents//Outputs: gross pay, each deduction, net pay////This is the 'repeat at user discretion' version//Outline://In a real payroll program, each of these values would be//stored in a file after the payroll calculation was printed //to a report.////regular payRate = $10.78/hour for hoursWorked <= 40//hours.//If hoursWorked > 40 hours,// overtimePay = (hoursWorked - 40) * 1.5 * PAY_RATE.//FICA (social security) tax rate is 6%//Federal income tax rate is 14%.//Union dues = $10/week .//If number of dependents >= 3// $15 more is withheld for dependent health insurance.//#include <iostream>using namespace std;const double PAY_RATE = 16.78;const double SS_TAX_RATE = 0.06;const double FedIRS_RATE = 0.14;const double STATE_TAX_RATE = 0.05;const double UNION_DUES = 10.0;const double OVERTIME_FACTOR = 1.5;const double HEALTH_INSURANCE = 15.0;int main(){double hoursWorked, grossPay, overTime, fica,incomeTax, stateTax, union_dues, netPay;int numberDependents, employeeNumber;char ans;//set the output to two places, and force .00 for cents cout.setf(ios::showpoint);cout.setf(ios::fixed);cout.precision(2);// compute payrolldo{cout << "Enter emplo yee SSN (digits only,”<< “ no spaces or dashes) \n”;cin >> employeeNumber ;cout << “Please the enter hours worked and number “<< “of employees.” << endl;cin >> hoursWorked ;cin >> numberDependents;cout << endl;if (hoursWorked <= 40 )grossPay = hoursWorked * PAY_RATE;else{overTime =(hoursWorked - 40) * PAY_RATE * OVERTIME_FACTOR; grossPay = 40 * PAY_RATE + overTime;}fica = grossPay * SS_TAX_RATE;incomeTax = grossPay * FedIRS_RATE;stateTax = grossPay * STATE_TAX_RATE;netPay =grossPay - fica - incomeTax- UNION_DUES - stateTax;if ( numberDependents >= 3 )netPay = netPay - HEALTH_INSURANCE;//now print report for this employee:cout << "Employee number: "<< employeeNumber << endl;cout << "hours worked: " << hoursWorked << endl; cout << "regular pay rate: " << PAY_RATE << endl;if (hoursWorked > 40 ){cout << "overtime hours worked: "<< hoursWorked - 40 << endl;cout << "with overtime premium: "<< OVERTIME_FACTOR << endl;}cout << "gross pay: " << grossPay << endl;cout << "FICA tax withheld: " << fica << endl;cout << "Federal Income Tax withheld: "<< incomeTax << endl;cout << "State Tax withheld: " << stateTax << endl;if (numberDependents >= 3 )cout << "Health Insurance Premium withheld: "<< HEALTH_INSURANCE << endl;cout << "Flabbergaster's Union Dues withheld: "<< UNION_DUES << endl;cout << "Net Pay: " << netPay << endl << endl;cout << "Compute pay for another employee?”<< “ Y/y repeats, any other ends" << endl;cin >> ans;} while( 'y' == ans || 'Y' == ans );return 0;}//A typical run:14:26:48:~/AW $ a.outEnter employee SSN (digits only, no spaces or dashes) 234567890Please the enter hours worked and number of employees.101Employee number: 234567890hours worked: 10.00regular pay rate: 16.78gross pay: 167.80FICA tax withheld: 10.07Federal Income Tax withheld: 23.49State Tax withheld: 8.39Flabbergaster's Union Dues withheld: 10.00Net Pay: 115.85Compute pay for another employee? Y/y repeats, any other ends yEnter employee SSN (digits only, no spaces or dashes) 987654321Please the enter hours worked and number of employees.103Employee number: 987654321hours worked: 10.00regular pay rate: 16.78gross pay: 167.80FICA tax withheld: 10.07Federal Income Tax withheld: 23.49State Tax withheld: 8.39Health Insurance Premium withheld: 35.00Flabbergaster's Union Dues withheld: 10.00Net Pay: 80.85Compute pay for another employee? Y/y repeats, any other ends yEnter employee SSN (digits only, no spaces or dashes) 123456789Please the enter hours worked and number of employees.453Employee number: 123456789hours worked: 45.00regular pay rate: 16.78overtime hours worked: 5.00with overtime premium: 1.50gross pay: 797.05FICA tax withheld: 47.82Federal Income Tax withheld: 111.59State Tax withheld: 39.85Health Insurance Premium withheld: 35.00Flabbergaster's Union Dues withheld: 10.00Net Pay: 552.79Compute pay for another employee? Y/y repeats, any other ends n14:28:12:~/AW $8. No solution provided.9. Installment Loan TimeNo down payment, 18 percent / year, payment of $50/month, payment goes first to interest, balance to principal. Write a program that determines the number of months it will take to pay off a $1000 stereo. The following code also outputs the monthly status of the loan.#include <iostream>using namespace std;// chapter 2 problem 9.int main(){double principal = 1000.;double interest, rate = 0.015;int months = 0;cout << "months\tinterest\tprincipal" << endl;while ( principal > 0 ){months++;interest = principal * rate;principal = principal - (50 - interest);if ( principal > 0 )cout << months << "\t" << interest << "\t\t"<< principal << endl;}cout << "number of payments = " << months;//undo the interation that drove principal negative: principal = principal + (50 - interest);//include interest for last month:interest = principal * 0.015;principal = principal + interest;cout << " last months interest = " << interest;cout << " last payment = " << principal << endl;return 0;}Testing is omitted for this problem.10. No solution provided.11. Separate numbers by sign, compute sums and averages// Programming Problem 11// Read ten int values output// sum and average of positive numbers// sum and average of nonpositive numbers,// sum and average of all numbers,//// Averages are usually floating point numbers.We mulitply// the numerator of the average computation by 1.0 to make// the int values convert automatically to double.#include <iostream>int main(){using std::cout;using std::cin;using std::endl;int value, sum = 0, sumPos = 0, sumNonPos = 0;int countPos = 0, countNeg = 0;cout << "Enter ten numbers, I'll echo your number and compute\n"<< "the sum and average of positive numbers\n"<< "the sum and average of nonpositive numbers\n"<< "the sum and average of all numbers\n\n";for(int i =0; i < 10; i++){cin >> value;cout << "value " << value <<endl;sum += value;if (value > 0){sumPos += value;countPos++;}else{sumNonPos += value;countNeg++;}}cout << "Sum of Positive numbers is "<< sumPos << endl;cout << "Average of Positive numbers is "<< (1.0 * sumPos) / countPos << endl;cout << "Sum of NonPositive numbers is "<< sumNonPos << endl;cout << "Average of NonPositive numbers is "<< (1.0 * sumNonPos) / countNeg << endl;cout << "Sum " << sum << endl;cout << "Average is " << (1.0 * sum)/(countPos + countNeg) << endl;if((countPos + countNeg)!= 10)cout << "Count not 10, error some place\n";return 0;}/*Typical runEnter ten numbers, I'll echo your number and computethe sum and average of positive numbersthe sum and average of nonpositive numbersthe sum and average of all numbers4value 45value 5-1value -13value 3-4value -4-3value -39value 98value 87value 72value 2Sum of Positive numbers is 38Average of Positive numbers is 5.42857Sum of NonPositive numbers is -8Average of NonPositive numbers is -2.66667Sum 30Average is 3Press any key to continue*/12.//***********************************************************************// Ch2Proj12.cpp//// This program computes the square root of a number n// using the Babylonian algorithm.//*********************************************************************** #include <iostream>using namespace std;// ====================// main function// ====================int main(){double guess, previousguess, n, r;// Input number to compute the square root ofcout << "Enter number to compute the square root of." << endl;cin >> n;// Initial guesspreviousguess = n;guess = n /2;// Repeat until guess is within 1% of the previous guesswhile (((previousguess - guess) / previousguess) > 0.01){previousguess = guess;r = n / guess;guess = (guess + r) / 2;}cout << "The estimate of the square root of " << n << " is "<< guess << endl;return 0;}13.//*********************************************************************** // Ch2Proj13.cpp//// This program inputs a speed in MPH and converts it to// Minutes and Seconds per mile, as might be output on a treadmill.//*********************************************************************** #include <iostream>using namespace std;// ====================// main function// ====================int main(){double milesPerHour, hoursPerMile, minutesPerMile, secondsPace;int minutesPace;// Input miles per hourcout << "Enter speed in miles per hour:" << endl;cin >> milesPerHour;// Compute inverse, which is hours per milehoursPerMile = 1.0 / milesPerHour;// Convert to minutes per mile which is 60 seconds/hour * hoursPerMile minutesPerMile = 60 * hoursPerMile;// Extract minutes by converting to an integer, while// truncates any value after the decimal pointminutesPace = static_cast<int>(minutesPerMile);// Seconds is the remaining number of minutes * 60secondsPace = (minutesPerMile - minutesPace) * 60;cout << milesPerHour << " miles per hour is a pace of " << minutesPace << " minutes and " << secondsPace << " seconds. " << endl;return 0;}14.//*********************************************************************** // Ch2Proj14.cpp//// This program plays a simple game of "Mad Libs".//*********************************************************************** #include <iostream>using namespace std;// ====================// main function// ====================int main(){string instructorName;string yourName;string food;int num;string adjective;string color;string animal;cout << "Welcome to Mad Libs! Enter your name: " << endl;cin >> yourName;cout << "Enter your instructor's first or last name." << endl;cin >> instructorName;cout << "Enter a food." << endl;cin >> food;cout << "Enter a number between 100 and 120." << endl;cin >> num;cout << "Enter an adjective." << endl;cin >> adjective;cout << "Enter a color." << endl;cin >> color;cout << "Enter an animal." << endl;cin >> animal;cout << endl;cout << "Dear Instructor " << instructorName << "," << endl;cout << endl;cout << "I am sorry that I am unable to turn in my homework at this time."<< endl;cout << "First, I ate a rotten " << food << " which made me turn " << color << " and " << endl;cout << "extremely ill. I came down with a fever of " << num << "." << endl;cout << "Next, my " << adjective << " pet " << animal << " must have " <<"smelled the remains " << endl;cout << "of the " << food << " on my homework, because he ate it. I am " <<"currently " << endl;cout << "rewriting my homework and hope you will accept it late." << endl;cout << endl;cout << "Sincerely," << endl;cout << yourName << endl;return 0;}2. Outline of topics in the chapter2.1 Variables and assignments2.2 Input and Output2.3 Data Types and Expressions2.4 Simple Flow of Controlbranchinglooping2.5 Program Style3. General Remarks on the chapter:This chapter is a very brief introduction to the minimum C++ necessary to write simple programs.Comments in the Student's code:Self documenting code is a code feature to be striven for. The use of identifier names that have meaning within the context of the problems being solved goes a long way in this direction.Code that is not self documenting for whatever reasons may be made clearer by appropriate (minimal) comments inserted in the code."The most difficult feature of any programming language to master is thecomment."-- a disgruntled maintenance programmer."Where the comment and the code disagree, both should be assumed to be inerror."-- an experienced maintenance programmer.With these cautions in mind, the student should place remarks at the top of file containing program components, describing the purpose. Exactly what output is required should be specified, and any conditions on the input to guarantee correct execution should also bespecified.Remarks can clarify difficult points, but remember, if the comment doesn't add to what can be gleaned from the program code itself, the comment is unnecessary, indeed it gets in the way. Good identifier names can reduce the necessity for comments!iostreams vs stdioYou will have the occasional student who has significant C programming experience. These students will insist on using the older stdio library input-output (for example, printf). Discourage this, insist on C++ iostream i/o. The reason is that the iostream library understands and uses the type system of C++. You have to tell stdio functions every type for every output attempted. And if you don't get it right, then the error may not be obvious in the output. Either iostreams knows the type, or the linker will complain that it doesn't have the member functions to handle the type you are using. Then it is easy enough to write stream i/o routines to do the i/o in a manner consistent with the rest of the library.。
面向对象程序设计java程序设计课后习题答案

第一章1.public class BegintoLearn{public static void main(String args[]) {System.out.println("I’d like to study Java ! ");}}2.public class TraStar{public static void main(String args[]) {System.out.println("*");System.out.println("* *");System.out.println("* * *");System.out.println("* * * *");System.out.println("* * * * *");}}第二章1.public class ProNum{public static void main(String args[]) {float p;long q;int m=10,n=5;System.out.println("m="+m+" n="+n);m=m+3;n=n+5;System.out.println("m="+m+" n="+n);p=(float)(m+n)/2;System.out.println("p="+p);q=(m*m*n*n);System.out.println("q="+q);}}2.class SphereClass {public static void main(String args[]) {int r=3;double v;v=3.14*r*r*r*4/3;System.out.println("V="+v)}}第三章1. import java.io.*;public class InNum{public static void main(String args[]) throws IOException{ int num1,num2;String str;BufferedReader buf;buf=new BufferedReader(new InputStreamReader(System.in));System.out.print("Input first integer:");str=buf.readLine();num1=Integer.parseInt(str);System.out.print("Input second integer:");str=buf.readLine();num2=Integer.parseInt(str);System.out.println("The sum is "+(num1+num2));}}2.import java.io.*;public class Grade{public static void main(String args[]) throws IOException{ int score;char ch;String str;BufferedReader buf;buf=new BufferedReader(new InputStreamReader(System.in));System.out.print("Input the score(0-100):");str=buf.readLine();score=Integer.parseInt(str);if (score>=90)ch='A';else if (score>=75)ch='B';else if (score>=60)ch='C';elsech='D';System.out.print("The Grade is "+ch);}}3.public class ShuLie{public static void main(String args[]){int a ,q ,n;q=(150-135)/5;a=(135-20*q)/5;for (n=0;n<10;n++)System.out.print((a+n*q)+" ");}}4.public class Pyramid{public static void main(String args[]){int i,j,k;for(i=0;i<=4;i++){for ( j=0;j<20-i;j++)System.out.print(" ");for (k=0;k<=2*i;k++)if (k<=i)System.out.print(" "+(2*k+1));elseSystem.out.print(" "+(2*(2*i-k)+1));System.out.println();}}}5.import java.io.*;public class PrimeNumber{public static void main(String args[]) throws IOException{ int n=0;int m;String str;boolean mark=false;BufferedReader buf;buf=new BufferedReader(new InputStreamReader(System.in));System.out.print("Input the m:");str=buf.readLine();m=Integer.parseInt(str);for(int i=3;i<=m;i+=2){for(int j=2;j<i;j++){if(i%j==0){mark=true;break;}}if (!mark){System.out.print(" "+i);n++; //outputanewlineif(n%10==0) //after10numbersSystem.out.println();}mark=false;}System.out.println();}}6.import java.io.*;public class Factor12{public static void main(String args[]) throws IOException{ int m;String str;BufferedReader buf;buf=new BufferedReader(new InputStreamReader(System.in));System.out.print("Input the m:");str=buf.readLine();m=Integer.parseInt(str);System.out.print(m+"\'s factors are: ");System.out.println( );for(int i=1;i<=m;i++)if (m%i==0)System.out.print(" "+i);}}7.public class MSteel{public static void main(String args[]){int d=0;float m=2000;while (m>=5) {m=m/2;d++;System.out.print(d+": ");System.out.println(m);}System.out.print("You need "+d+" days");}}8.public class AlmostPi{public static void main(String args[]){int n;long m;double s,t;n=1;m=0;s=0;do{t=(double)n/(2*m+1);m++;n=-n;s=s+t;} while (4*s-3.14159> 0.0000001 || 4*s-3.14159< -0.0000001);System.out.println(m);}}9.public class LSRnd{public static void main(String args[]){int mun,n,max1,min1;max1=0;min1=100;for (n=1;n<=10;n++){mun=(int)(100*Math.random());System.out.print(mun+" ");if (mun>max1)max1=mun;if (mun<min1)min1=mun;}System.out.println();System.out.println("The largest number is: "+max1);System.out.println("The smallest number is: "+min1);}}10.import java.io.*;public class StrArry{public static void main(String args[]) throws IOException{int m;String str;Stringmonth[]={"January","February","March","April","May","June","July","August","september","October","November","December"};BufferedReader buf;buf=new BufferedReader(new InputStreamReader(System.in));System.out.print("Input the m:");str=buf.readLine();m=Integer.parseInt(str);if (m>=1 && m<=12)System.out.println(month[m-1]);elseSystem.out.print("Your Input is wrong");}}第四章1.import java.util.*;public class Person{private String name;private char sex;private int year,month;public Person( ){}public Person(String nm,char sx,int y,int m) {name=nm;sex=sx;year=y;month=m;}public void printPerson( ) {Calendar now=Calendar.getInstance();int age=now.get(Calendar.YEAR)-year;System.out.println("Name: "+name+",Sex: "+sex+", Age: "+age);}public static void main(String args[]){Person pe1=new Person("Tom",'m',1980,10);pe1.printPerson();}}2.public class Rectangle{double width,length,girth,area;public Rectangle(){};public Rectangle(double wd,double le) {width=wd;length=le;}public void setWidth(double wd) {width=wd;}public void setLength(double le) {length=le;}public double getWidth( ) {return width;}public double getLength( ) {return length;}public double girth(){return 2*(width+length);}public double area(){return width*length;}public void printRectangle(){System.out.println("Width="+width+" ,Length="+length);}public static void main(String args[]){Rectangle re1=new Rectangle(10,20);Rectangle re2=new Rectangle();re2.setWidth(3);re2.setLength(4);re1.printRectangle();System.out.println("Girth="+re1.girth()+",Area="+re1.area());re2.printRectangle();System.out.println("Girth="+re2.girth()+",Area="+re2.area());}}3.public class Matrix{ private int mx[][],m,n; public Matrix(int r,int c) { m=r;n=c;mx=new int[m][n];iniMatrix();}public Matrix(){m=3;n=3;mx=new int[3][3];iniMatrix();}public void iniMatrix(){ int i,j;for(i=0;i<=m-1;i++)for(j=0;j<=n-1;j++)mx[i][j]=(int)(Math.random()*100); }public void tranMatrix(){int i,j,t;int mt[][]=new int[m][n];for(i=0;i<=m-1;i++)for(j=0;j<=n-1;j++)mt[i][j]=mx[i][j];t=m;m=n;n=t;mx=new int[m][n];for(i=0;i<=m-1;i++)for(j=0;j<=n-1;j++)mx[i][j]=mt[j][i];}public void printMatrix(){int i,j;for(i=0;i<=m-1;i++){for(j=0;j<=n-1;j++)System.out.print(" "+mx[i][j]);System.out.println();}}public void addMatrix(Matrix b) {int i,j;for(i=0;i<=m-1;i++)for(j=0;j<=n-1;j++)mx[i][j]=mx[i][j]+b.mx[i][j];} public static void main(String args[]){Matrix ma=new Matrix(4,3);Matrix mb=new Matrix(4,3);System.out.println("The matrix_A:"); ma.printMatrix();System.out.println("The matrix_B:"); mb.printMatrix();System.out.println("Matrix_A +Matrix_B:");ma.addMatrix(mb);ma.printMatrix();System.out.println("Transpose Matrix_B:");mb.tranMatrix();mb.printMatrix();}}4.public class Substring{public static void main(String args[]){String str1=new String("addActionListener");String str2=new String("Action");int n;n=str1.indexOf(str2);if(n>=0){System.out.println("String_2 is in String_1");System.out.println("The substring before String_2 is "+str1.substring(0,n));System.out.println("The substring behind String_2 is "+str1.substring(n+str2.length( )));}}} 五、写出程序运行后的结果1. 2.。
Visual C++程序设计案例教程第二章课后答案

(4)已知CTest类定义如下,t是CTest类的对象,则正确的成员访问是。(A)
class CTest {
public:
void SetA(int x)
{ a=x; }
private:
int a;
};
A. t.SetA(10)
B. t.a
C. t-> SetA(10)
(5)继承是通过基类与派生类来实现的。基类的成员在派生类中的访问权限由___继承方式___决定。
(6)派生类的对象可以当成____基类____的对象来处理,因此,指向_____基类______对象的指针也可以指向派生类的对象。
(7)对基类对象成员的初始化是通过___构造函数_____语法实现的。
(8)如果一个类中含有纯虚函数,则称该类为________抽象类______。
};
<各个成员函数的实现>
对象的定义格式:类名对象名;
(2)分析构造函数和析构函数的作用。
构造函数:用于创建和初始化实例;析构函数:析构函数用于销毁类的实例。
(3)简述基类和派生类关系。
任何一个类都可以派生出一个新类,派生类也可以再派生出新类,因此,基类和派生类是相对而言的。 基类与派生类之间的关系有:a:派生类是基类的具体化b:派生类是基类定义的延续c:派生类是基类的组合
};
class Point:public CShape
{
public:
Point(float a,float b);
virtual float area();
virtual float volume();
virtual void show();
面向对象程序设计第二章课后答案说课讲解

面向对象程序设计第二章课后答案1.什么是命名空间,如何访问命名空间的成员?【解答】为了解决不同文件中同名变量的问题,C++标准中引入命名空间的概念。
命名空间(namespace)是一种特殊的作用域,命名空间可以由程序员自己来创建,可以将不同的标识符集合在一个命名作用域内,这些标识符可以类、对象、函数、变量、结构体、模板以及其他命名空间等。
在作用域范围内使用命名空间就可以访问命名空间定义的标识符。
有3种访问方法:(1)直接指定标识符,访问方式为:命名空间标识符名∷成员名。
(2)使用using namespace命令(3)使用using关键词声明2.什么是内联函数,它有什么特点?哪些函数不能定义为内联函数?【解答】用inline关键字声明或定义的函数称为内联函数。
C++中对于功能简单、规模小、使用频繁的函数,可以将其设置为内联函数。
内联函数(inline function)的定义和普通函数相同,但C++对它们的处理方式不一样。
在编译时,C++将用内联函数程序代码替换对它每次的调用。
这样,内联函数没有函数调用的开销,即节省参数传递、控制转移的开销,从而提高了程序运行时的效率。
但是,由于每次调用内联函数时,需要将这个内联函数的所有代码复制到调用函数中,所以会增加程序的代码量,占用更多的存储空间,增大了系统空间方面的开销。
因此,内联函数是一种空间换时间的方案。
函数体内有循环语句和switch语句,递归调用的函数不能定义为内联函数。
3.什么是函数重载?在函数调用时,C++是如何匹配重载函数的?【解答】函数重载是指两个或两个以上的函数具有相同的函数名,但参数类型不一致或参数个数不同。
编译时编译器将根据实参和形参的类型及个数进行相应地匹配,自动确定调用哪一个函数。
使得重载的函数虽然函数名相同,但功能却不完全相同。
在函数调用时,C++是匹配重载函数规则如下:首先寻找一个精确匹配,如果能找到,调用该函数;其次进行提升匹配,通过内部类型转换(窄类型到宽类型的转换)寻求一个匹配,如char到int、short到int等,如果能找到,调用该函数;最后通过强制类型转换寻求一个匹配,如果能找到,调用该函数。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
1.什么是命名空间,如何访问命名空间的成员?【解答】为了解决不同文件中同名变量的问题,C++标准中引入命名空间的概念。
命名空间(namespace)是一种特殊的作用域,命名空间可以由程序员自己来创建,可以将不同的标识符集合在一个命名作用域内,这些标识符可以类、对象、函数、变量、结构体、模板以及其他命名空间等。
在作用域范围内使用命名空间就可以访问命名空间定义的标识符。
有3种访问方法:(1)直接指定标识符,访问方式为:命名空间标识符名∷成员名。
(2)使用using namespace命令(3)使用using关键词声明2.什么是内联函数,它有什么特点?哪些函数不能定义为内联函数?【解答】用inline关键字声明或定义的函数称为内联函数。
C++中对于功能简单、规模小、使用频繁的函数,可以将其设置为内联函数。
内联函数(inline function)的定义和普通函数相同,但C++对它们的处理方式不一样。
在编译时,C++将用内联函数程序代码替换对它每次的调用。
这样,内联函数没有函数调用的开销,即节省参数传递、控制转移的开销,从而提高了程序运行时的效率。
但是,由于每次调用内联函数时,需要将这个内联函数的所有代码复制到调用函数中,所以会增加程序的代码量,占用更多的存储空间,增大了系统空间方面的开销。
因此,内联函数是一种空间换时间的方案。
函数体内有循环语句和switch语句,递归调用的函数不能定义为内联函数。
3.什么是函数重载?在函数调用时,C++是如何匹配重载函数的?【解答】函数重载是指两个或两个以上的函数具有相同的函数名,但参数类型不一致或参数个数不同。
编译时编译器将根据实参和形参的类型及个数进行相应地匹配,自动确定调用哪一个函数。
使得重载的函数虽然函数名相同,但功能却不完全相同。
在函数调用时,C++是匹配重载函数规则如下:首先寻找一个精确匹配,如果能找到,调用该函数;其次进行提升匹配,通过内部类型转换(窄类型到宽类型的转换)寻求一个匹配,如char到int、short到int等,如果能找到,调用该函数;最后通过强制类型转换寻求一个匹配,如果能找到,调用该函数。
4.设置函数参数的默认值有何作用?【解答】C++中允许函数提供默认参数,也就是允许在函数的声明或定义时给一个或多个参数指定默认值。
在调用具有默认参数的函数时,如果没有提供实际参数,C++将自动把默认参数作为相应参数的值5.什么叫引用,使用引用时需要注意哪些问题?【解答】引用是一个变量的别名。
使用引用时,必须在定义时进行初始化,不能在定义完后再赋值。
6.new运算符的作用是什么?delete运算符的作用是什么?【解答】在C++程序中,new是动态分配内存的运算符,自动计算需要分配的空间。
delete是撤销动态申请的内存运算符。
delete与new通常配对使用,建立堆对象时使用new运算符、删除堆对象时delete使用运算符。
7、#include"stdafx.h"#include"iostream"using namespace std;int Min(int x1,int x2);int Min(int x1,int x2,int x3);int Min(int x1,int x2,int x3,int x4); int _tmain(int argc, _TCHAR* argv[]) {int x1,x2,x3,x4;cout<<"input x1,x2,x3,x4"<<endl; cin>>x1>>x2>>x3>>x4;cout<<Min(x1,x2)<<endl;cout<<Min(x2,x3,x4)<<endl;cout<<Min(x1,x2,x3,x4)<<endl;getchar();return 0;}int Min(int x1,int x2){return (x1<x2?x1:x2);}int Min(int x1,int x2,int x3){int y;y=x1<x2?x1:x2;return (y<x3?y:x3);}int Min(int x1,int x2,int x3,int x4) {int y1,y2;y1=x1<x2?x1:x2;y2=x3<x4?x3:x4;return (y1<y2?y1:y2);}8、#include“stdafx.h”#include"iostream"#include<cmath>using namespace std;#define pi 3.141592double Area(double R);double Area(double a,double b);double Perim(double R);double Perim(double a,double b);int _tmain(int argc, _TCHAR* argv[]) { double r;double m;double n;cout<<"请输入圆的半径"<<endl;cin>>r;cout<<"圆的面积为:"<<Area(r)<<" "<<"圆的周长为:"<<Perim(r) <<endl;cout<<"请输入长方形的边长"<<endl;cin>>m>>n;cout<<"长方形的面积为:"<<Area(m,n)<<" "<<"长方形的周长为:"<<Perim(m,n)<<endl;cout<<"请输入正方形的边长"<<endl;cin>>m;cout<<"正方形的面积为:"<<Area(m,m)<<" "<<"正方形的周长为:"<<Perim(m,m)<<endl;return 0;}double Area(double R){ double s;s=pi*R*R;return s;}double Area(double a,double b){ double s;s=a*b;return s;}double Perim(double R){ double p;p=2*pi*R;return p;}double Perim(double a,double b){ double p;p=2*(a+b);return p;}9、#include<fstream>#include<iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){ofstream outData("D:\\data.txt");ifstream inData;int x,i,b[10];for(i=0;i<10;i++){ cin>>x;outData<<x<<" "; }outData.close();inData.open("D:\\data.txt");//while(!inData.eof())for(int j=0;j<10;j++){inData>>b[j];} inData.close();int s=0;for(int m=0;m<10;m++){ s+=b[m];cout<<b[m]<<" "; }cout<<endl;cout<<"数据总和为:"<<s<<endl;getchar();return 0;}10、(1)#include<fstream>#include<iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){ofstream outData("C:\\student.dat"); //char name[8],id[10],pro[8];int math,english;for(int i=0;i<3;i++){ cout<<"输入学生姓名:";cin>>name;cout<<"输入学生学号:";cin>>id;cout<<"输入学生专业:";cin>>pro;cout<<"输入高数成绩:";cin>>math;cout<<"输入英语成绩:";cin>>english;outData<<name<<" "<<id<<" "<<pro<<" "<<math<<" "<<english<<endl;}outData.close();return 0;}(2)#include<fstream>#include<iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){ifstream inData("C:\\student.dat");char name1[8],id1[10],pro1[8];int math1,english1;for(int i=0;i<8;i++){inData>>name1>>id1>>pro1>>math1>>english1;cout<<"姓名:"<<name1<<endl;cout<<"学号:"<<id1<<endl;cout<<"专业:"<<pro1<<endl;cout<<"高数成绩:"<<math1<<endl;cout<<"英语成绩:"<<english1<<endl;}inData.close();getchar();return 0;}。